repo
string
commit
string
message
string
diff
string
VsVim/VsVim
8d38a15e6fc0f86df1314dd1b03022eee9e34fcc
Add test: marks after paste.
diff --git a/Test/VimCoreTest/VimBufferTest.cs b/Test/VimCoreTest/VimBufferTest.cs index 8b8149d..c6f99ae 100644 --- a/Test/VimCoreTest/VimBufferTest.cs +++ b/Test/VimCoreTest/VimBufferTest.cs @@ -5,1059 +5,1076 @@ using Microsoft.FSharp.Core; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Vim.Extensions; using Vim.Interpreter; using Xunit; namespace Vim.UnitTest { public abstract class VimBufferTest : VimTestBase { private ITextView _textView; private VimBuffer _vimBufferRaw; private IVimBuffer _vimBuffer; private MockRepository _factory; private IVimLocalKeyMap _localKeyMap; public VimBufferTest() { _textView = CreateTextView("here we go"); _textView.MoveCaretTo(0); _vimBuffer = Vim.CreateVimBuffer(_textView); _vimBuffer.SwitchMode(ModeKind.Command, ModeArgument.None); _localKeyMap = _vimBuffer.LocalKeyMap; _vimBufferRaw = (VimBuffer)_vimBuffer; _factory = new MockRepository(MockBehavior.Strict); } private Mock<INormalMode> CreateAndAddNormalMode(MockBehavior behavior = MockBehavior.Strict) { var mode = _factory.Create<INormalMode>(behavior); mode.SetupGet(x => x.ModeKind).Returns(ModeKind.Normal); mode.SetupGet(x => x.KeyRemapMode).Returns(KeyRemapMode.Normal); mode.SetupGet(x => x.InCount).Returns(false); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBufferRaw.NormalMode); _vimBufferRaw.AddMode(mode.Object); return mode; } private Mock<IInsertMode> CreateAndAddInsertMode(MockBehavior behavior = MockBehavior.Strict) { var mode = _factory.Create<IInsertMode>(behavior); mode.SetupGet(x => x.ModeKind).Returns(ModeKind.Insert); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBuffer.InsertMode); _vimBufferRaw.AddMode(mode.Object); return mode; } private Mock<IVisualMode> CreateAndAddVisualLineMode(MockBehavior behavior = MockBehavior.Strict) { var mode = _factory.Create<IVisualMode>(behavior); mode.SetupGet(x => x.ModeKind).Returns(ModeKind.VisualLine); mode.SetupGet(x => x.KeyRemapMode).Returns(KeyRemapMode.Visual); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBuffer.VisualLineMode); _vimBufferRaw.AddMode(mode.Object); return mode; } public sealed class KeyInputTest : VimBufferTest { public KeyInputTest() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); } /// <summary> /// Make sure the processed event is raised during a key process /// </summary> [WpfFact] public void ProcessedFires() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var ran = false; _vimBuffer.KeyInputProcessed += delegate { ran = true; }; _vimBuffer.Process('l'); Assert.True(ran); } /// <summary> /// Make sure the events are raised in order /// </summary> [WpfFact] public void EventOrderForNormal() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var start = false; var processed = false; var end = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.False(processed || end); start = true; }; _vimBuffer.KeyInputProcessed += (b, args) => { var keyInput = args.KeyInput; Assert.Equal('l', keyInput.Char); Assert.True(start && !end); processed = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start && processed); end = true; }; _vimBuffer.Process('l'); Assert.True(start && processed && end); } /// <summary> /// Start and End events should fire even if there is an exception thrown /// </summary> [WpfFact] public void ExceptionDuringProcessing() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.IsAny<KeyInputData>())).Throws(new Exception()); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var start = false; var end = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(!end); start = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start); end = true; }; var caught = false; try { _vimBuffer.Process('l'); } catch (Exception) { caught = true; } Assert.True(start && end && caught); } /// <summary> /// Start, Buffered and End should fire if the KeyInput is buffered due to /// a mapping /// </summary> [WpfFact] public void BufferedInput() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("lad", "rad", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("hello world"); var start = false; var processed = false; var end = false; var buffered = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(!buffered && !end); start = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start && buffered); end = true; }; _vimBuffer.KeyInputBuffered += (b, args) => { Assert.Equal('l', args.KeyInputSet.FirstKeyInput.Value.Char); Assert.True(start && !end); buffered = true; }; _vimBuffer.KeyInputProcessed += delegate { processed = true; }; _vimBuffer.Process('l'); Assert.True(start && buffered && end && !processed); } /// <summary> /// When KeyInputStart is handled we still need to fire the other 3 events (Processing, Processed and End) in the /// proper order. The naiive consumer should see this is a normal event sequence /// </summary> [WpfFact] public void KeyInputStartHandled() { var count = 0; _vimBuffer.KeyInputStart += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(0, count); count++; e.Handled = true; }; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(1, count); Assert.True(e.Handled); count++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(2, count); count++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(3, count); count++; }; _vimBuffer.Process('c'); Assert.Equal(4, count); } /// <summary> /// When KeyInputProcessing is handled we still need to fire the other 2 events (Processed and End) in the /// proper order. The naiive consumer should see this is a normal event sequence /// </summary> [WpfFact] public void KeyInputProcessingHandled() { var count = 0; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(0, count); e.Handled = true; count++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(1, count); count++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(2, count); count++; }; _vimBuffer.Process('c'); Assert.Equal(3, count); } /// <summary> /// The start and end events shouldn't consider any mappings. They should display the key /// which was actually pressed. The Processing events though should consider the mappings /// </summary> [WpfFact] public void Mappings() { var seen = 0; _vimBuffer.ProcessNotation(":map a b", enter: true); _vimBuffer.KeyInputStart += (sender, e) => { Assert.Equal('a', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('a', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('b', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('b', e.KeyInput.Char); seen++; }; _vimBuffer.ProcessNotation("a"); Assert.Equal(4, seen); } } public sealed class CloseTest : VimBufferTest { /// <summary> /// Close should call OnLeave and OnClose for the active IMode /// </summary> [WpfFact] public void ShouldCallLeaveAndClose() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); normal.Setup(x => x.OnLeave()).Verifiable(); normal.Setup(x => x.OnClose()).Verifiable(); _vimBuffer.Close(); normal.Verify(); } /// <summary> /// Close should call IMode::Close for every IMode even the ones which /// are not active /// </summary> [WpfFact] public void CallCloseOnAll() { var insert = CreateAndAddInsertMode(); insert.Setup(x => x.OnClose()).Verifiable(); _vimBuffer.Close(); insert.Verify(); } /// <summary> /// The IVimBuffer should be removed from IVim on close /// </summary> [WpfFact] public void BufferShouldBeRemoved() { var didSee = false; _vimBuffer.Closed += delegate { didSee = true; }; _vimBuffer.Close(); Assert.True(didSee); } /// <summary> /// Closing the buffer while not processing input should raise PostClosed event. /// </summary> [WpfFact] public void ExternalCloseShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; _vimBuffer.Close(); Assert.Equal(1, count); } /// <summary> /// Closing the buffer while processing input should also raise PostClosed event. /// </summary> [WpfFact] public void ProcessCloseCommandShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; var normal = CreateAndAddNormalMode(MockBehavior.Loose); int keyCount = 0; normal.Setup(x => x.Process(It.IsAny<KeyInputData>())) .Callback(() => { if (keyCount == 0) { keyCount = 1; _vimBuffer.Process("Q"); Assert.Equal(0, count); } else _vimBuffer.Close(); }) .Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("Q"); Assert.Equal(1, count); } /// <summary> /// Closing the buffer while processing buffered key input should raise PostClosed event. /// </summary> [WpfFact] public void ProcessBufferedCloseCommandShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.Is<KeyInputData>(k => k.KeyInput.Equals(KeyInputUtil.CharToKeyInput('A'))))) .Callback(() => { _vimBuffer.Close(); }) .Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("Q", "A", allowRemap: false, KeyRemapMode.Normal); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("QQ", "B", allowRemap: false, KeyRemapMode.Normal); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("Q"); Assert.Equal(0, count); _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(1, count); } /// <summary> /// Double close should throw /// </summary> [WpfFact] public void DoubleClose() { _vimBuffer.Close(); Assert.Throws<InvalidOperationException>(() => _vimBuffer.Close()); } [WpfFact] public void CloseEventOrder() { var count = 0; _vimBuffer.Closing += delegate { Assert.False(_vimBuffer.IsClosed); Assert.Equal(0, count); count++; }; _vimBuffer.Closed += delegate { Assert.Equal(1, count); count++; }; _vimBuffer.Close(); Assert.Equal(2, count); } /// <summary> /// An exception in closing should be ignored. /// </summary> [WpfFact] public void ExceptionInClosing() { var count = 0; _vimBuffer.Closing += delegate { Assert.False(_vimBuffer.IsClosed); Assert.Equal(0, count); count++; throw new Exception(); }; _vimBuffer.Closed += delegate { Assert.Equal(1, count); count++; }; _vimBuffer.Close(); Assert.Equal(2, count); } } public class SpecialMarks : ClosingSetsLastEditedPositionMark { [WpfFact] public void SpecialMarksAreSet() { var s_emptyList = FSharpList<Mark>.Empty; OpenFakeVimBufferTestWindow(""); var interpreter = new VimInterpreter( _vimBuffer, CommonOperationsFactory.GetCommonOperations(_vimBufferData), FoldManagerFactory.GetFoldManager(_vimBufferData.TextView), new FileSystem(), BufferTrackingService); _vimBuffer.ProcessNotation("<ESC>i1<CR>2<CR>3<CR>4<CR>5<CR>6<CR>7<CR>8<CR>9<CR>0<ESC>"); interpreter.RunDisplayMarks(s_emptyList); var expectedMarks = new[] { @"mark line col file/text", @" ' 1 0 1", @" "" 1 0 1", @" [ 1 0 1", @" ] 10 1 0", @" ^ 10 1 0", @" . 10 0 0", }; Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); // set an upper (line 8) and lower mark (line 9) _vimBuffer.ProcessNotation("kmzkmZ"); // jump from line 8 to line 1 and yank it. - // jump mark and [ ] must be set + // jump mark and [ ] must be updated _vimBuffer.ProcessNotation("1Gyy"); interpreter.RunDisplayMarks(s_emptyList); expectedMarks = new[] { @"mark line col file/text", @" ' 8 0 8", @" z 9 0 9", @" Z 8 0 VimBufferTest.cs", @" "" 1 0 1", @" [ 1 0 1", @" ] 1 1 1", @" ^ 10 1 0", @" . 10 0 0", }; Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); - // visual line mode to test these marks + // select lines 3,4 in visual line mode to test marks <, > _vimBuffer.ProcessNotation("jjVj<ESC>"); interpreter.RunDisplayMarks(s_emptyList); - interpreter.RunDisplayMarks(s_emptyList); expectedMarks = new[] { @"mark line col file/text", @" ' 8 0 8", @" z 9 0 9", @" Z 8 0 VimBufferTest.cs", @" "" 1 0 1", @" [ 1 0 1", @" ] 1 1 1", @" ^ 10 1 0", @" . 10 0 0", @" < 3 0 3", @" > 4 1 4", }; Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); + // jump to last line and paste before to check that marks [ ] are updated + _vimBuffer.ProcessNotation("GP"); + interpreter.RunDisplayMarks(s_emptyList); + expectedMarks = new[] { + @"mark line col file/text", + @" ' 3 0 8", + @" z 9 0 9", + @" Z 8 0 VimBufferTest.cs", + @" "" 1 0 1", + @" [ 10 0 1", + @" ] 10 1 1", + @" ^ 11 1 0", + @" . 10 1 1", + @" < 3 0 3", + @" > 4 1 4", + }; + Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); + //_vimBuffer.ProcessNotation("yy"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 8 0 8", // @" z 9 0 9", // @" Z 8 0 VimBufferTest.cs", // @" "" 1 0 1", // @" [ 1 0 1", // @" ] 1 1 1", // @" ^ 10 1 0", // @" . 10 0 0", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); // set an upper and lower mark one line 2 and 3 //_vimBuffer.ProcessNotation("jmajmA2k"); // we paste one first line, so we know : text = line + 1 //_vimBuffer.ProcessNotation("P"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 9 0 8", // @" a 3 0 2", // @" z 10 0 9", // @" A 4 0 VimBufferTest.cs", // @" Z 9 0 VimBufferTest.cs", // @" "" 1 0 1", // @" [ 7 0 1", // @" ] 7 1 1", // @" ^ 11 1 0", // @" . 1 1 1", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); //_vimBuffer.ProcessNotation("kV<ESC>"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 9 0 VimBufferTest.cs", // @" a 2 0 VimBufferTest.cs", // @" z 10 0 VimBufferTest.cs", // @" A 3 0 VimBufferTest.cs", // @" Z 9 0 VimBufferTest.cs", // @" "" 1 0 VimBufferTest.cs", // @" [ 7 0 VimBufferTest.cs", // @" ] 7 1 VimBufferTest.cs", // @" ^ 11 1 VimBufferTest.cs", // @" . 7 1 VimBufferTest.cs", // @" < 6 0 VimBufferTest.cs", // @" > 6 1 VimBufferTest.cs", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); } } public class ClosingSetsLastEditedPositionMark : VimBufferTest { protected TestableStatusUtil _statusUtil = new TestableStatusUtil(); protected IVimBufferData _vimBufferData; public ClosingSetsLastEditedPositionMark() { OpenFakeVimBufferTestWindow(); _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 0, 0); } protected void OpenFakeVimBufferTestWindow() { OpenFakeVimBufferTestWindow("Hello", "World!"); } protected void OpenFakeVimBufferTestWindow(params string[] lines) { _textView = CreateTextView(lines); _textView.MoveCaretTo(0); _textView.TextBuffer.Properties.AddProperty(Mock.MockVimHost.FileNameKey, "VimBufferTest.cs"); _vimBufferData = CreateVimBufferData(_textView, statusUtil: _statusUtil); _vimBuffer = CreateVimBuffer(_vimBufferData); _vimBuffer.SwitchMode(ModeKind.Command, ModeArgument.None); } protected void AssertPosition(int lineNumber, int column, FSharpOption<VirtualSnapshotPoint> option) { Assert.True(option.IsSome()); var line = VirtualSnapshotPointUtil.GetPoint(option.Value).GetColumn(); Assert.Equal(lineNumber, line.LineNumber); Assert.Equal(column, line.ColumnNumber); } [WpfFact] public void FirstTimeBufferIsZeroZero() { var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } [WpfFact] public void ReopeningTheWindow() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 2, option); } [WpfFact] public void ReopeningTheWindowLastColumn() { _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 0, 5); OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 5, option); } [WpfFact] public void ReopeningTheWindowLastColumnAfterFirstLine() { _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 1, 6); OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 6, option); } [WpfFact] public void ReopeningTheWindowLastPositionAtColumnZeroWithLenZeroIsOk() { _textView.SetText("Hello", "", "World!"); _textView.MoveCaretToLine(1, 0); _vimBuffer.Close(); // reopen the file OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 0, option); } [WpfFact] public void ReopeningTheWindowWithInvalidColumnLastPositionGoesToZeroZero() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file to invalid column position OpenFakeVimBufferTestWindow("Hello", ""); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } [WpfFact] public void ReopeningTheWindowWithInvalidLineLastPositionGoesToZeroZero() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file to invalid line position OpenFakeVimBufferTestWindow("Hello"); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } } public class UnloadedMarksTest : ClosingSetsLastEditedPositionMark { [WpfFact] public void ReloadUnloadedMark() { Vim.MarkMap.SetGlobalMark(Letter.A, _vimBufferData.VimTextBuffer, 1, 2); AssertPosition(1, 2, Vim.MarkMap.GetGlobalMark(Letter.A)); _vimBuffer.Close(); Assert.True(Vim.MarkMap.GetGlobalMark(Letter.A).IsNone()); // reopen the file OpenFakeVimBufferTestWindow(); AssertPosition(1, 2, Vim.MarkMap.GetGlobalMark(Letter.A)); } } public sealed class MiscTest : VimBufferTest { /// <summary> /// Make sure the SwitchdMode event fires when switching modes. /// </summary> [WpfFact] public void SwitchedMode_Event() { var ran = false; _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(ran); } /// <summary> /// Make sure the SwitchdMode event fires even when switching to the /// same mode /// </summary> [WpfFact] public void SwitchedMode_SameModeEvent() { var ran = false; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(ran); } /// <summary> /// Ensure switching to the previous mode operates correctly /// </summary> [WpfFact] public void SwitchPreviousMode_EnterLeaveOrder() { var normal = CreateAndAddNormalMode(); var insert = CreateAndAddInsertMode(); normal.Setup(x => x.OnEnter(ModeArgument.None)).Verifiable(); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); normal.Verify(); normal.Setup(x => x.OnLeave()); insert.Setup(x => x.OnEnter(ModeArgument.None)); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); normal.Verify(); insert.Verify(); insert.Setup(x => x.OnLeave()).Verifiable(); var prev = _vimBuffer.SwitchPreviousMode(); Assert.Same(normal.Object, prev); insert.Verify(); // On tear down all IVimBuffer instances are closed as well as their active // IMode. Need a setup here insert.Setup(x => x.OnClose()); normal.Setup(x => x.OnClose()); } /// <summary> /// SwitchPreviousMode should raise the SwitchedMode event /// </summary> [WpfFact] public void SwitchPreviousMode_RaiseSwitchedMode() { _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); var ran = false; _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchPreviousMode(); Assert.True(ran); } /// <summary> /// When a mode returns the SwitchModeOneTimeCommand value it should cause the /// InOneTimeCommand value to be set /// </summary> [WpfFact] public void SwitchModeOneTimeCommand_SetProperty() { var mode = CreateAndAddInsertMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.NewSwitchModeOneTimeCommand(ModeKind.Normal))); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); _vimBuffer.Process('c'); Assert.True(_vimBuffer.InOneTimeCommand.IsSome(ModeKind.Insert)); } /// <summary> /// Process should handle the return value correctly /// </summary> [WpfFact] public void Process_HandleSwitchPreviousMode() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.SwitchPreviousMode)); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('l'); Assert.Equal(ModeKind.Command, _vimBuffer.ModeKind); } /// <summary> /// The nop key shouldn't have any effects /// </summary> [WpfFact] public void Process_Nop() { var old = _vimBuffer.TextSnapshot; foreach (var mode in _vimBuffer.AllModes) { _vimBuffer.SwitchMode(mode.ModeKind, ModeArgument.None); Assert.True(_vimBuffer.Process(VimKey.Nop)); Assert.Equal(old, _vimBuffer.TextSnapshot); } } /// <summary> /// When we are InOneTimeCommand the HandledNeedMoreInput should not cause us to /// do anything with respect to one time command /// </summary> [WpfFact] public void Process_OneTimeCommand_NeedMoreInputDoesNothing() { var mode = CreateAndAddNormalMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.HandledNeedMoreInput); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('c'); Assert.True(_vimBufferRaw.InOneTimeCommand.IsSome(ModeKind.Replace)); } /// <summary> /// Escape should go back to the original mode even if the current IMode doesn't /// support the escape key when we are in a one time command /// </summary> [WpfFact] public void Process_OneTimeCommand_Escape() { var mode = CreateAndAddNormalMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.Error); mode.Setup(x => x.CanProcess(It.IsAny<KeyInput>())).Returns(false); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process(VimKey.Escape); Assert.Equal(ModeKind.Replace, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.IsNone()); } /// <summary> /// When a command is completed in visual mode we shouldn't exit. Else commands like /// 'l' would cause it to exit which is not the Vim behavior /// </summary> [WpfFact] public void Process_OneTimeCommand_VisualMode_Handled() { var mode = CreateAndAddVisualLineMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.SwitchMode(ModeKind.VisualLine, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('l'); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.Is(ModeKind.Replace)); } /// <summary> /// Switch previous mode should still cause it to go back to the original though /// </summary> [WpfFact] public void Process_OneTimeCommand_VisualMode_SwitchPreviousMode() { var mode = CreateAndAddVisualLineMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.SwitchPreviousMode)); _vimBuffer.SwitchMode(ModeKind.VisualLine, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('l'); Assert.Equal(ModeKind.Replace, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.IsNone()); } /// <summary> /// Processing the buffered key inputs when there are none should have no effect /// </summary> [WpfFact] public void ProcessBufferedKeyInputs_Nothing() { var runCount = 0; _vimBuffer.KeyInputProcessed += delegate { runCount++; }; _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(0, runCount); } /// <summary> /// Processing the buffered key inputs should raise the processed event /// </summary> [WpfFact] public void ProcessBufferedKeyInputs_RaiseProcessed() { var runCount = 0; _textView.SetText(""); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("cat", "chase the cat", allowRemap: false, KeyRemapMode.Insert); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); _vimBuffer.KeyInputProcessed += delegate { runCount++; }; _vimBuffer.Process("ca"); Assert.Equal(0, runCount); _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(2, runCount); Assert.Equal("ca", _textView.GetLine(0).GetText()); } /// <summary> /// Ensure the mode sees the mapped KeyInput value /// </summary> [WpfFact] public void Remap_OneToOne() { _localKeyMap.AddKeyMapping("a", "l", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// When a single key is mapped to multiple both need to be passed onto the /// IMode instance /// </summary> [WpfFact] public void Remap_OneToMany() { _localKeyMap.AddKeyMapping("a", "dw", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Don't use mappings for the wrong IMode /// </summary> [WpfFact] public void Remap_WrongMode() { _localKeyMap.AddKeyMapping("l", "dw", allowRemap: false, KeyRemapMode.Insert); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('l'); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// When INormalMode is in OperatorPending we need to use operating pending /// remapping /// </summary> [WpfFact] public void Remap_OperatorPending() { _localKeyMap.AddKeyMapping("z", "w", allowRemap: false, KeyRemapMode.OperatorPending); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("d"); Assert.Equal(_vimBuffer.NormalMode.KeyRemapMode, KeyRemapMode.OperatorPending); _vimBuffer.Process("z"); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Recursive mappings should print out an error message when used /// </summary> [WpfFact] public void Remap_Recursive() { _localKeyMap.AddKeyMapping("a", "b", allowRemap: true, KeyRemapMode.Normal); _localKeyMap.AddKeyMapping("b", "a", allowRemap: true, KeyRemapMode.Normal); var didRun = false; _vimBuffer.ErrorMessage += (notUsed, args) => { Assert.Equal(Resources.Vim_RecursiveMapping, args.Message); didRun = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.True(didRun); } /// <summary> /// When we buffer input and fail to find a mapping every KeyInput value /// should be passed to the IMode /// </summary> [WpfFact] public void Remap_BufferedFailed() { _localKeyMap.AddKeyMapping("do", "cat", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("d"); Assert.Equal('d', _vimBuffer.BufferedKeyInputs.Head.Char); _vimBuffer.Process("w"); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Make sure the KeyInput is passed down to the IMode /// </summary> [WpfFact] public void CanProcess_Simple() { var keyInput = KeyInputUtil.CharToKeyInput('c'); var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.CanProcess(keyInput)).Returns(true).Verifiable(); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(_vimBuffer.CanProcess(keyInput)); normal.Verify(); } /// <summary> /// Make sure the mapped KeyInput is passed down to the IMode /// </summary> [WpfFact] public void CanProcess_Mapped() { _localKeyMap.AddKeyMapping("a", "c", allowRemap: true, KeyRemapMode.Normal); var keyInput = KeyInputUtil.CharToKeyInput('c'); var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.CanProcess(keyInput)).Returns(true).Verifiable(); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(_vimBuffer.CanProcess('a'));
VsVim/VsVim
a9a05cc8ec5de67a884535f143eddab336ac28f3
Fix visual mark test.
diff --git a/Test/VimCoreTest/VimBufferTest.cs b/Test/VimCoreTest/VimBufferTest.cs index 816afed..8b8149d 100644 --- a/Test/VimCoreTest/VimBufferTest.cs +++ b/Test/VimCoreTest/VimBufferTest.cs @@ -36,1025 +36,1025 @@ namespace Vim.UnitTest mode.SetupGet(x => x.ModeKind).Returns(ModeKind.Normal); mode.SetupGet(x => x.KeyRemapMode).Returns(KeyRemapMode.Normal); mode.SetupGet(x => x.InCount).Returns(false); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBufferRaw.NormalMode); _vimBufferRaw.AddMode(mode.Object); return mode; } private Mock<IInsertMode> CreateAndAddInsertMode(MockBehavior behavior = MockBehavior.Strict) { var mode = _factory.Create<IInsertMode>(behavior); mode.SetupGet(x => x.ModeKind).Returns(ModeKind.Insert); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBuffer.InsertMode); _vimBufferRaw.AddMode(mode.Object); return mode; } private Mock<IVisualMode> CreateAndAddVisualLineMode(MockBehavior behavior = MockBehavior.Strict) { var mode = _factory.Create<IVisualMode>(behavior); mode.SetupGet(x => x.ModeKind).Returns(ModeKind.VisualLine); mode.SetupGet(x => x.KeyRemapMode).Returns(KeyRemapMode.Visual); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBuffer.VisualLineMode); _vimBufferRaw.AddMode(mode.Object); return mode; } public sealed class KeyInputTest : VimBufferTest { public KeyInputTest() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); } /// <summary> /// Make sure the processed event is raised during a key process /// </summary> [WpfFact] public void ProcessedFires() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var ran = false; _vimBuffer.KeyInputProcessed += delegate { ran = true; }; _vimBuffer.Process('l'); Assert.True(ran); } /// <summary> /// Make sure the events are raised in order /// </summary> [WpfFact] public void EventOrderForNormal() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var start = false; var processed = false; var end = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.False(processed || end); start = true; }; _vimBuffer.KeyInputProcessed += (b, args) => { var keyInput = args.KeyInput; Assert.Equal('l', keyInput.Char); Assert.True(start && !end); processed = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start && processed); end = true; }; _vimBuffer.Process('l'); Assert.True(start && processed && end); } /// <summary> /// Start and End events should fire even if there is an exception thrown /// </summary> [WpfFact] public void ExceptionDuringProcessing() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.IsAny<KeyInputData>())).Throws(new Exception()); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var start = false; var end = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(!end); start = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start); end = true; }; var caught = false; try { _vimBuffer.Process('l'); } catch (Exception) { caught = true; } Assert.True(start && end && caught); } /// <summary> /// Start, Buffered and End should fire if the KeyInput is buffered due to /// a mapping /// </summary> [WpfFact] public void BufferedInput() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("lad", "rad", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("hello world"); var start = false; var processed = false; var end = false; var buffered = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(!buffered && !end); start = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start && buffered); end = true; }; _vimBuffer.KeyInputBuffered += (b, args) => { Assert.Equal('l', args.KeyInputSet.FirstKeyInput.Value.Char); Assert.True(start && !end); buffered = true; }; _vimBuffer.KeyInputProcessed += delegate { processed = true; }; _vimBuffer.Process('l'); Assert.True(start && buffered && end && !processed); } /// <summary> /// When KeyInputStart is handled we still need to fire the other 3 events (Processing, Processed and End) in the /// proper order. The naiive consumer should see this is a normal event sequence /// </summary> [WpfFact] public void KeyInputStartHandled() { var count = 0; _vimBuffer.KeyInputStart += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(0, count); count++; e.Handled = true; }; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(1, count); Assert.True(e.Handled); count++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(2, count); count++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(3, count); count++; }; _vimBuffer.Process('c'); Assert.Equal(4, count); } /// <summary> /// When KeyInputProcessing is handled we still need to fire the other 2 events (Processed and End) in the /// proper order. The naiive consumer should see this is a normal event sequence /// </summary> [WpfFact] public void KeyInputProcessingHandled() { var count = 0; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(0, count); e.Handled = true; count++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(1, count); count++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(2, count); count++; }; _vimBuffer.Process('c'); Assert.Equal(3, count); } /// <summary> /// The start and end events shouldn't consider any mappings. They should display the key /// which was actually pressed. The Processing events though should consider the mappings /// </summary> [WpfFact] public void Mappings() { var seen = 0; _vimBuffer.ProcessNotation(":map a b", enter: true); _vimBuffer.KeyInputStart += (sender, e) => { Assert.Equal('a', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('a', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('b', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('b', e.KeyInput.Char); seen++; }; _vimBuffer.ProcessNotation("a"); Assert.Equal(4, seen); } } public sealed class CloseTest : VimBufferTest { /// <summary> /// Close should call OnLeave and OnClose for the active IMode /// </summary> [WpfFact] public void ShouldCallLeaveAndClose() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); normal.Setup(x => x.OnLeave()).Verifiable(); normal.Setup(x => x.OnClose()).Verifiable(); _vimBuffer.Close(); normal.Verify(); } /// <summary> /// Close should call IMode::Close for every IMode even the ones which /// are not active /// </summary> [WpfFact] public void CallCloseOnAll() { var insert = CreateAndAddInsertMode(); insert.Setup(x => x.OnClose()).Verifiable(); _vimBuffer.Close(); insert.Verify(); } /// <summary> /// The IVimBuffer should be removed from IVim on close /// </summary> [WpfFact] public void BufferShouldBeRemoved() { var didSee = false; _vimBuffer.Closed += delegate { didSee = true; }; _vimBuffer.Close(); Assert.True(didSee); } /// <summary> /// Closing the buffer while not processing input should raise PostClosed event. /// </summary> [WpfFact] public void ExternalCloseShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; _vimBuffer.Close(); Assert.Equal(1, count); } /// <summary> /// Closing the buffer while processing input should also raise PostClosed event. /// </summary> [WpfFact] public void ProcessCloseCommandShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; var normal = CreateAndAddNormalMode(MockBehavior.Loose); int keyCount = 0; normal.Setup(x => x.Process(It.IsAny<KeyInputData>())) .Callback(() => { if (keyCount == 0) { keyCount = 1; _vimBuffer.Process("Q"); Assert.Equal(0, count); } else _vimBuffer.Close(); }) .Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("Q"); Assert.Equal(1, count); } /// <summary> /// Closing the buffer while processing buffered key input should raise PostClosed event. /// </summary> [WpfFact] public void ProcessBufferedCloseCommandShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.Is<KeyInputData>(k => k.KeyInput.Equals(KeyInputUtil.CharToKeyInput('A'))))) .Callback(() => { _vimBuffer.Close(); }) .Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("Q", "A", allowRemap: false, KeyRemapMode.Normal); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("QQ", "B", allowRemap: false, KeyRemapMode.Normal); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("Q"); Assert.Equal(0, count); _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(1, count); } /// <summary> /// Double close should throw /// </summary> [WpfFact] public void DoubleClose() { _vimBuffer.Close(); Assert.Throws<InvalidOperationException>(() => _vimBuffer.Close()); } [WpfFact] public void CloseEventOrder() { var count = 0; _vimBuffer.Closing += delegate { Assert.False(_vimBuffer.IsClosed); Assert.Equal(0, count); count++; }; _vimBuffer.Closed += delegate { Assert.Equal(1, count); count++; }; _vimBuffer.Close(); Assert.Equal(2, count); } /// <summary> /// An exception in closing should be ignored. /// </summary> [WpfFact] public void ExceptionInClosing() { var count = 0; _vimBuffer.Closing += delegate { Assert.False(_vimBuffer.IsClosed); Assert.Equal(0, count); count++; throw new Exception(); }; _vimBuffer.Closed += delegate { Assert.Equal(1, count); count++; }; _vimBuffer.Close(); Assert.Equal(2, count); } } public class SpecialMarks : ClosingSetsLastEditedPositionMark { [WpfFact] public void SpecialMarksAreSet() { var s_emptyList = FSharpList<Mark>.Empty; OpenFakeVimBufferTestWindow(""); var interpreter = new VimInterpreter( _vimBuffer, CommonOperationsFactory.GetCommonOperations(_vimBufferData), FoldManagerFactory.GetFoldManager(_vimBufferData.TextView), new FileSystem(), BufferTrackingService); _vimBuffer.ProcessNotation("<ESC>i1<CR>2<CR>3<CR>4<CR>5<CR>6<CR>7<CR>8<CR>9<CR>0<ESC>"); interpreter.RunDisplayMarks(s_emptyList); var expectedMarks = new[] { @"mark line col file/text", @" ' 1 0 1", @" "" 1 0 1", @" [ 1 0 1", @" ] 10 1 0", @" ^ 10 1 0", @" . 10 0 0", }; Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); // set an upper (line 8) and lower mark (line 9) _vimBuffer.ProcessNotation("kmzkmZ"); // jump from line 8 to line 1 and yank it. // jump mark and [ ] must be set _vimBuffer.ProcessNotation("1Gyy"); interpreter.RunDisplayMarks(s_emptyList); expectedMarks = new[] { @"mark line col file/text", @" ' 8 0 8", @" z 9 0 9", @" Z 8 0 VimBufferTest.cs", @" "" 1 0 1", @" [ 1 0 1", @" ] 1 1 1", @" ^ 10 1 0", @" . 10 0 0", }; Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); // visual line mode to test these marks _vimBuffer.ProcessNotation("jjVj<ESC>"); interpreter.RunDisplayMarks(s_emptyList); interpreter.RunDisplayMarks(s_emptyList); expectedMarks = new[] { @"mark line col file/text", @" ' 8 0 8", @" z 9 0 9", @" Z 8 0 VimBufferTest.cs", @" "" 1 0 1", @" [ 1 0 1", @" ] 1 1 1", @" ^ 10 1 0", @" . 10 0 0", @" < 3 0 3", - @" > 4 2 4", + @" > 4 1 4", }; Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); //_vimBuffer.ProcessNotation("yy"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 8 0 8", // @" z 9 0 9", // @" Z 8 0 VimBufferTest.cs", // @" "" 1 0 1", // @" [ 1 0 1", // @" ] 1 1 1", // @" ^ 10 1 0", // @" . 10 0 0", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); // set an upper and lower mark one line 2 and 3 //_vimBuffer.ProcessNotation("jmajmA2k"); // we paste one first line, so we know : text = line + 1 //_vimBuffer.ProcessNotation("P"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 9 0 8", // @" a 3 0 2", // @" z 10 0 9", // @" A 4 0 VimBufferTest.cs", // @" Z 9 0 VimBufferTest.cs", // @" "" 1 0 1", // @" [ 7 0 1", // @" ] 7 1 1", // @" ^ 11 1 0", // @" . 1 1 1", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); //_vimBuffer.ProcessNotation("kV<ESC>"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 9 0 VimBufferTest.cs", // @" a 2 0 VimBufferTest.cs", // @" z 10 0 VimBufferTest.cs", // @" A 3 0 VimBufferTest.cs", // @" Z 9 0 VimBufferTest.cs", // @" "" 1 0 VimBufferTest.cs", // @" [ 7 0 VimBufferTest.cs", // @" ] 7 1 VimBufferTest.cs", // @" ^ 11 1 VimBufferTest.cs", // @" . 7 1 VimBufferTest.cs", // @" < 6 0 VimBufferTest.cs", // @" > 6 1 VimBufferTest.cs", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); } } public class ClosingSetsLastEditedPositionMark : VimBufferTest { protected TestableStatusUtil _statusUtil = new TestableStatusUtil(); protected IVimBufferData _vimBufferData; public ClosingSetsLastEditedPositionMark() { OpenFakeVimBufferTestWindow(); _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 0, 0); } protected void OpenFakeVimBufferTestWindow() { OpenFakeVimBufferTestWindow("Hello", "World!"); } protected void OpenFakeVimBufferTestWindow(params string[] lines) { _textView = CreateTextView(lines); _textView.MoveCaretTo(0); _textView.TextBuffer.Properties.AddProperty(Mock.MockVimHost.FileNameKey, "VimBufferTest.cs"); _vimBufferData = CreateVimBufferData(_textView, statusUtil: _statusUtil); _vimBuffer = CreateVimBuffer(_vimBufferData); _vimBuffer.SwitchMode(ModeKind.Command, ModeArgument.None); } protected void AssertPosition(int lineNumber, int column, FSharpOption<VirtualSnapshotPoint> option) { Assert.True(option.IsSome()); var line = VirtualSnapshotPointUtil.GetPoint(option.Value).GetColumn(); Assert.Equal(lineNumber, line.LineNumber); Assert.Equal(column, line.ColumnNumber); } [WpfFact] public void FirstTimeBufferIsZeroZero() { var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } [WpfFact] public void ReopeningTheWindow() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 2, option); } [WpfFact] public void ReopeningTheWindowLastColumn() { _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 0, 5); OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 5, option); } [WpfFact] public void ReopeningTheWindowLastColumnAfterFirstLine() { _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 1, 6); OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 6, option); } [WpfFact] public void ReopeningTheWindowLastPositionAtColumnZeroWithLenZeroIsOk() { _textView.SetText("Hello", "", "World!"); _textView.MoveCaretToLine(1, 0); _vimBuffer.Close(); // reopen the file OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 0, option); } [WpfFact] public void ReopeningTheWindowWithInvalidColumnLastPositionGoesToZeroZero() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file to invalid column position OpenFakeVimBufferTestWindow("Hello", ""); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } [WpfFact] public void ReopeningTheWindowWithInvalidLineLastPositionGoesToZeroZero() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file to invalid line position OpenFakeVimBufferTestWindow("Hello"); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } } public class UnloadedMarksTest : ClosingSetsLastEditedPositionMark { [WpfFact] public void ReloadUnloadedMark() { Vim.MarkMap.SetGlobalMark(Letter.A, _vimBufferData.VimTextBuffer, 1, 2); AssertPosition(1, 2, Vim.MarkMap.GetGlobalMark(Letter.A)); _vimBuffer.Close(); Assert.True(Vim.MarkMap.GetGlobalMark(Letter.A).IsNone()); // reopen the file OpenFakeVimBufferTestWindow(); AssertPosition(1, 2, Vim.MarkMap.GetGlobalMark(Letter.A)); } } public sealed class MiscTest : VimBufferTest { /// <summary> /// Make sure the SwitchdMode event fires when switching modes. /// </summary> [WpfFact] public void SwitchedMode_Event() { var ran = false; _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(ran); } /// <summary> /// Make sure the SwitchdMode event fires even when switching to the /// same mode /// </summary> [WpfFact] public void SwitchedMode_SameModeEvent() { var ran = false; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(ran); } /// <summary> /// Ensure switching to the previous mode operates correctly /// </summary> [WpfFact] public void SwitchPreviousMode_EnterLeaveOrder() { var normal = CreateAndAddNormalMode(); var insert = CreateAndAddInsertMode(); normal.Setup(x => x.OnEnter(ModeArgument.None)).Verifiable(); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); normal.Verify(); normal.Setup(x => x.OnLeave()); insert.Setup(x => x.OnEnter(ModeArgument.None)); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); normal.Verify(); insert.Verify(); insert.Setup(x => x.OnLeave()).Verifiable(); var prev = _vimBuffer.SwitchPreviousMode(); Assert.Same(normal.Object, prev); insert.Verify(); // On tear down all IVimBuffer instances are closed as well as their active // IMode. Need a setup here insert.Setup(x => x.OnClose()); normal.Setup(x => x.OnClose()); } /// <summary> /// SwitchPreviousMode should raise the SwitchedMode event /// </summary> [WpfFact] public void SwitchPreviousMode_RaiseSwitchedMode() { _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); var ran = false; _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchPreviousMode(); Assert.True(ran); } /// <summary> /// When a mode returns the SwitchModeOneTimeCommand value it should cause the /// InOneTimeCommand value to be set /// </summary> [WpfFact] public void SwitchModeOneTimeCommand_SetProperty() { var mode = CreateAndAddInsertMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.NewSwitchModeOneTimeCommand(ModeKind.Normal))); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); _vimBuffer.Process('c'); Assert.True(_vimBuffer.InOneTimeCommand.IsSome(ModeKind.Insert)); } /// <summary> /// Process should handle the return value correctly /// </summary> [WpfFact] public void Process_HandleSwitchPreviousMode() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.SwitchPreviousMode)); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('l'); Assert.Equal(ModeKind.Command, _vimBuffer.ModeKind); } /// <summary> /// The nop key shouldn't have any effects /// </summary> [WpfFact] public void Process_Nop() { var old = _vimBuffer.TextSnapshot; foreach (var mode in _vimBuffer.AllModes) { _vimBuffer.SwitchMode(mode.ModeKind, ModeArgument.None); Assert.True(_vimBuffer.Process(VimKey.Nop)); Assert.Equal(old, _vimBuffer.TextSnapshot); } } /// <summary> /// When we are InOneTimeCommand the HandledNeedMoreInput should not cause us to /// do anything with respect to one time command /// </summary> [WpfFact] public void Process_OneTimeCommand_NeedMoreInputDoesNothing() { var mode = CreateAndAddNormalMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.HandledNeedMoreInput); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('c'); Assert.True(_vimBufferRaw.InOneTimeCommand.IsSome(ModeKind.Replace)); } /// <summary> /// Escape should go back to the original mode even if the current IMode doesn't /// support the escape key when we are in a one time command /// </summary> [WpfFact] public void Process_OneTimeCommand_Escape() { var mode = CreateAndAddNormalMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.Error); mode.Setup(x => x.CanProcess(It.IsAny<KeyInput>())).Returns(false); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process(VimKey.Escape); Assert.Equal(ModeKind.Replace, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.IsNone()); } /// <summary> /// When a command is completed in visual mode we shouldn't exit. Else commands like /// 'l' would cause it to exit which is not the Vim behavior /// </summary> [WpfFact] public void Process_OneTimeCommand_VisualMode_Handled() { var mode = CreateAndAddVisualLineMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.SwitchMode(ModeKind.VisualLine, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('l'); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.Is(ModeKind.Replace)); } /// <summary> /// Switch previous mode should still cause it to go back to the original though /// </summary> [WpfFact] public void Process_OneTimeCommand_VisualMode_SwitchPreviousMode() { var mode = CreateAndAddVisualLineMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.SwitchPreviousMode)); _vimBuffer.SwitchMode(ModeKind.VisualLine, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('l'); Assert.Equal(ModeKind.Replace, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.IsNone()); } /// <summary> /// Processing the buffered key inputs when there are none should have no effect /// </summary> [WpfFact] public void ProcessBufferedKeyInputs_Nothing() { var runCount = 0; _vimBuffer.KeyInputProcessed += delegate { runCount++; }; _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(0, runCount); } /// <summary> /// Processing the buffered key inputs should raise the processed event /// </summary> [WpfFact] public void ProcessBufferedKeyInputs_RaiseProcessed() { var runCount = 0; _textView.SetText(""); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("cat", "chase the cat", allowRemap: false, KeyRemapMode.Insert); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); _vimBuffer.KeyInputProcessed += delegate { runCount++; }; _vimBuffer.Process("ca"); Assert.Equal(0, runCount); _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(2, runCount); Assert.Equal("ca", _textView.GetLine(0).GetText()); } /// <summary> /// Ensure the mode sees the mapped KeyInput value /// </summary> [WpfFact] public void Remap_OneToOne() { _localKeyMap.AddKeyMapping("a", "l", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// When a single key is mapped to multiple both need to be passed onto the /// IMode instance /// </summary> [WpfFact] public void Remap_OneToMany() { _localKeyMap.AddKeyMapping("a", "dw", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Don't use mappings for the wrong IMode /// </summary> [WpfFact] public void Remap_WrongMode() { _localKeyMap.AddKeyMapping("l", "dw", allowRemap: false, KeyRemapMode.Insert); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('l'); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// When INormalMode is in OperatorPending we need to use operating pending /// remapping /// </summary> [WpfFact] public void Remap_OperatorPending() { _localKeyMap.AddKeyMapping("z", "w", allowRemap: false, KeyRemapMode.OperatorPending); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("d"); Assert.Equal(_vimBuffer.NormalMode.KeyRemapMode, KeyRemapMode.OperatorPending); _vimBuffer.Process("z"); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Recursive mappings should print out an error message when used /// </summary> [WpfFact] public void Remap_Recursive() { _localKeyMap.AddKeyMapping("a", "b", allowRemap: true, KeyRemapMode.Normal); _localKeyMap.AddKeyMapping("b", "a", allowRemap: true, KeyRemapMode.Normal); var didRun = false; _vimBuffer.ErrorMessage += (notUsed, args) => { Assert.Equal(Resources.Vim_RecursiveMapping, args.Message); didRun = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.True(didRun); } /// <summary> /// When we buffer input and fail to find a mapping every KeyInput value /// should be passed to the IMode /// </summary> [WpfFact] public void Remap_BufferedFailed() { _localKeyMap.AddKeyMapping("do", "cat", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("d"); Assert.Equal('d', _vimBuffer.BufferedKeyInputs.Head.Char); _vimBuffer.Process("w"); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Make sure the KeyInput is passed down to the IMode /// </summary> [WpfFact] public void CanProcess_Simple() { var keyInput = KeyInputUtil.CharToKeyInput('c'); var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.CanProcess(keyInput)).Returns(true).Verifiable(); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(_vimBuffer.CanProcess(keyInput)); normal.Verify(); } /// <summary> /// Make sure the mapped KeyInput is passed down to the IMode /// </summary> [WpfFact] public void CanProcess_Mapped() { _localKeyMap.AddKeyMapping("a", "c", allowRemap: true, KeyRemapMode.Normal); var keyInput = KeyInputUtil.CharToKeyInput('c'); var normal = CreateAndAddNormalMode(MockBehavior.Loose);
VsVim/VsVim
4063b902c764e272c8eed9aacb563db5ac51ae8a
Enable test again.
diff --git a/Test/VimCoreTest/VimBufferTest.cs b/Test/VimCoreTest/VimBufferTest.cs index d5d338f..9a6b7df 100644 --- a/Test/VimCoreTest/VimBufferTest.cs +++ b/Test/VimCoreTest/VimBufferTest.cs @@ -4,1034 +4,1036 @@ using Microsoft.FSharp.Collections; using Microsoft.FSharp.Core; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Vim.Extensions; using Vim.Interpreter; using Xunit; namespace Vim.UnitTest { public abstract class VimBufferTest : VimTestBase { private ITextView _textView; private VimBuffer _vimBufferRaw; private IVimBuffer _vimBuffer; private MockRepository _factory; private IVimLocalKeyMap _localKeyMap; public VimBufferTest() { _textView = CreateTextView("here we go"); _textView.MoveCaretTo(0); _vimBuffer = Vim.CreateVimBuffer(_textView); _vimBuffer.SwitchMode(ModeKind.Command, ModeArgument.None); _localKeyMap = _vimBuffer.LocalKeyMap; _vimBufferRaw = (VimBuffer)_vimBuffer; _factory = new MockRepository(MockBehavior.Strict); } private Mock<INormalMode> CreateAndAddNormalMode(MockBehavior behavior = MockBehavior.Strict) { var mode = _factory.Create<INormalMode>(behavior); mode.SetupGet(x => x.ModeKind).Returns(ModeKind.Normal); mode.SetupGet(x => x.KeyRemapMode).Returns(KeyRemapMode.Normal); mode.SetupGet(x => x.InCount).Returns(false); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBufferRaw.NormalMode); _vimBufferRaw.AddMode(mode.Object); return mode; } private Mock<IInsertMode> CreateAndAddInsertMode(MockBehavior behavior = MockBehavior.Strict) { var mode = _factory.Create<IInsertMode>(behavior); mode.SetupGet(x => x.ModeKind).Returns(ModeKind.Insert); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBuffer.InsertMode); _vimBufferRaw.AddMode(mode.Object); return mode; } private Mock<IVisualMode> CreateAndAddVisualLineMode(MockBehavior behavior = MockBehavior.Strict) { var mode = _factory.Create<IVisualMode>(behavior); mode.SetupGet(x => x.ModeKind).Returns(ModeKind.VisualLine); mode.SetupGet(x => x.KeyRemapMode).Returns(KeyRemapMode.Visual); mode.Setup(x => x.OnLeave()); mode.Setup(x => x.OnClose()); _vimBufferRaw.RemoveMode(_vimBuffer.VisualLineMode); _vimBufferRaw.AddMode(mode.Object); return mode; } public sealed class KeyInputTest : VimBufferTest { public KeyInputTest() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); } /// <summary> /// Make sure the processed event is raised during a key process /// </summary> [WpfFact] public void ProcessedFires() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var ran = false; _vimBuffer.KeyInputProcessed += delegate { ran = true; }; _vimBuffer.Process('l'); Assert.True(ran); } /// <summary> /// Make sure the events are raised in order /// </summary> [WpfFact] public void EventOrderForNormal() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var start = false; var processed = false; var end = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.False(processed || end); start = true; }; _vimBuffer.KeyInputProcessed += (b, args) => { var keyInput = args.KeyInput; Assert.Equal('l', keyInput.Char); Assert.True(start && !end); processed = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start && processed); end = true; }; _vimBuffer.Process('l'); Assert.True(start && processed && end); } /// <summary> /// Start and End events should fire even if there is an exception thrown /// </summary> [WpfFact] public void ExceptionDuringProcessing() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.IsAny<KeyInputData>())).Throws(new Exception()); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _textView.SetText("hello world"); var start = false; var end = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(!end); start = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start); end = true; }; var caught = false; try { _vimBuffer.Process('l'); } catch (Exception) { caught = true; } Assert.True(start && end && caught); } /// <summary> /// Start, Buffered and End should fire if the KeyInput is buffered due to /// a mapping /// </summary> [WpfFact] public void BufferedInput() { _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("lad", "rad", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("hello world"); var start = false; var processed = false; var end = false; var buffered = false; _vimBuffer.KeyInputStart += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(!buffered && !end); start = true; }; _vimBuffer.KeyInputEnd += (b, args) => { Assert.Equal('l', args.KeyInput.Char); Assert.True(start && buffered); end = true; }; _vimBuffer.KeyInputBuffered += (b, args) => { Assert.Equal('l', args.KeyInputSet.FirstKeyInput.Value.Char); Assert.True(start && !end); buffered = true; }; _vimBuffer.KeyInputProcessed += delegate { processed = true; }; _vimBuffer.Process('l'); Assert.True(start && buffered && end && !processed); } /// <summary> /// When KeyInputStart is handled we still need to fire the other 3 events (Processing, Processed and End) in the /// proper order. The naiive consumer should see this is a normal event sequence /// </summary> [WpfFact] public void KeyInputStartHandled() { var count = 0; _vimBuffer.KeyInputStart += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(0, count); count++; e.Handled = true; }; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(1, count); Assert.True(e.Handled); count++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(2, count); count++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(3, count); count++; }; _vimBuffer.Process('c'); Assert.Equal(4, count); } /// <summary> /// When KeyInputProcessing is handled we still need to fire the other 2 events (Processed and End) in the /// proper order. The naiive consumer should see this is a normal event sequence /// </summary> [WpfFact] public void KeyInputProcessingHandled() { var count = 0; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(0, count); e.Handled = true; count++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(1, count); count++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('c', e.KeyInput.Char); Assert.Equal(2, count); count++; }; _vimBuffer.Process('c'); Assert.Equal(3, count); } /// <summary> /// The start and end events shouldn't consider any mappings. They should display the key /// which was actually pressed. The Processing events though should consider the mappings /// </summary> [WpfFact] public void Mappings() { var seen = 0; _vimBuffer.ProcessNotation(":map a b", enter: true); _vimBuffer.KeyInputStart += (sender, e) => { Assert.Equal('a', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputEnd += (sender, e) => { Assert.Equal('a', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputProcessing += (sender, e) => { Assert.Equal('b', e.KeyInput.Char); seen++; }; _vimBuffer.KeyInputProcessed += (sender, e) => { Assert.Equal('b', e.KeyInput.Char); seen++; }; _vimBuffer.ProcessNotation("a"); Assert.Equal(4, seen); } } public sealed class CloseTest : VimBufferTest { /// <summary> /// Close should call OnLeave and OnClose for the active IMode /// </summary> [WpfFact] public void ShouldCallLeaveAndClose() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); normal.Setup(x => x.OnLeave()).Verifiable(); normal.Setup(x => x.OnClose()).Verifiable(); _vimBuffer.Close(); normal.Verify(); } /// <summary> /// Close should call IMode::Close for every IMode even the ones which /// are not active /// </summary> [WpfFact] public void CallCloseOnAll() { var insert = CreateAndAddInsertMode(); insert.Setup(x => x.OnClose()).Verifiable(); _vimBuffer.Close(); insert.Verify(); } /// <summary> /// The IVimBuffer should be removed from IVim on close /// </summary> [WpfFact] public void BufferShouldBeRemoved() { var didSee = false; _vimBuffer.Closed += delegate { didSee = true; }; _vimBuffer.Close(); Assert.True(didSee); } /// <summary> /// Closing the buffer while not processing input should raise PostClosed event. /// </summary> [WpfFact] public void ExternalCloseShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; _vimBuffer.Close(); Assert.Equal(1, count); } /// <summary> /// Closing the buffer while processing input should also raise PostClosed event. /// </summary> [WpfFact] public void ProcessCloseCommandShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; var normal = CreateAndAddNormalMode(MockBehavior.Loose); int keyCount = 0; normal.Setup(x => x.Process(It.IsAny<KeyInputData>())) .Callback(() => { if (keyCount == 0) { keyCount = 1; _vimBuffer.Process("Q"); Assert.Equal(0, count); } else _vimBuffer.Close(); }) .Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("Q"); Assert.Equal(1, count); } /// <summary> /// Closing the buffer while processing buffered key input should raise PostClosed event. /// </summary> [WpfFact] public void ProcessBufferedCloseCommandShouldRaisePostClosed() { var count = 0; _vimBuffer.PostClosed += delegate { count++; }; var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.Is<KeyInputData>(k => k.KeyInput.Equals(KeyInputUtil.CharToKeyInput('A'))))) .Callback(() => { _vimBuffer.Close(); }) .Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("Q", "A", allowRemap: false, KeyRemapMode.Normal); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("QQ", "B", allowRemap: false, KeyRemapMode.Normal); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("Q"); Assert.Equal(0, count); _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(1, count); } /// <summary> /// Double close should throw /// </summary> [WpfFact] public void DoubleClose() { _vimBuffer.Close(); Assert.Throws<InvalidOperationException>(() => _vimBuffer.Close()); } [WpfFact] public void CloseEventOrder() { var count = 0; _vimBuffer.Closing += delegate { Assert.False(_vimBuffer.IsClosed); Assert.Equal(0, count); count++; }; _vimBuffer.Closed += delegate { Assert.Equal(1, count); count++; }; _vimBuffer.Close(); Assert.Equal(2, count); } /// <summary> /// An exception in closing should be ignored. /// </summary> [WpfFact] public void ExceptionInClosing() { var count = 0; _vimBuffer.Closing += delegate { Assert.False(_vimBuffer.IsClosed); Assert.Equal(0, count); count++; throw new Exception(); }; _vimBuffer.Closed += delegate { Assert.Equal(1, count); count++; }; _vimBuffer.Close(); Assert.Equal(2, count); } } public class SpecialMarks : ClosingSetsLastEditedPositionMark { [WpfFact] public void SpecialMarksAreSet() { var s_emptyList = FSharpList<Mark>.Empty; OpenFakeVimBufferTestWindow(""); var interpreter = new VimInterpreter( _vimBuffer, CommonOperationsFactory.GetCommonOperations(_vimBufferData), FoldManagerFactory.GetFoldManager(_vimBufferData.TextView), new FileSystem(), BufferTrackingService); _vimBuffer.ProcessNotation("<ESC>i1<CR>2<CR>3<CR>4<CR>5<CR>6<CR>7<CR>8<CR>9<CR>0<ESC>"); interpreter.RunDisplayMarks(s_emptyList); var expectedMarks = new[] { @"mark line col file/text", @" ' 1 0 1", @" "" 1 0 1", @" [ 1 0 1", @" ] 10 1 0", @" ^ 10 1 0", @" . 10 0 0", }; Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); // set an upper and lower mark _vimBuffer.ProcessNotation("kmzkmZ"); - _vimBuffer.ProcessNotation("1G"); + // jump to line 1 and yank it. + // jump mark and [ ] must be set + _vimBuffer.ProcessNotation("1Gyy"); interpreter.RunDisplayMarks(s_emptyList); expectedMarks = new[] { @"mark line col file/text", @" ' 8 0 8", @" z 9 0 9", @" Z 8 0 VimBufferTest.cs", @" "" 1 0 1", @" [ 1 0 1", - @" ] 10 1 0", + @" ] 0 1 1", @" ^ 10 1 0", @" . 10 0 0", }; Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); //_vimBuffer.ProcessNotation("yy"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 8 0 8", // @" z 9 0 9", // @" Z 8 0 VimBufferTest.cs", // @" "" 1 0 1", // @" [ 1 0 1", // @" ] 1 1 1", // @" ^ 10 1 0", // @" . 10 0 0", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); // set an upper and lower mark one line 2 and 3 //_vimBuffer.ProcessNotation("jmajmA2k"); // we paste one first line, so we know : text = line + 1 //_vimBuffer.ProcessNotation("P"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 9 0 8", // @" a 3 0 2", // @" z 10 0 9", // @" A 4 0 VimBufferTest.cs", // @" Z 9 0 VimBufferTest.cs", // @" "" 1 0 1", // @" [ 7 0 1", // @" ] 7 1 1", // @" ^ 11 1 0", // @" . 1 1 1", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); //_vimBuffer.ProcessNotation("kV<ESC>"); //interpreter.RunDisplayMarks(s_emptyList); //expectedMarks = new[] { // @"mark line col file/text", // @" ' 9 0 VimBufferTest.cs", // @" a 2 0 VimBufferTest.cs", // @" z 10 0 VimBufferTest.cs", // @" A 3 0 VimBufferTest.cs", // @" Z 9 0 VimBufferTest.cs", // @" "" 1 0 VimBufferTest.cs", // @" [ 7 0 VimBufferTest.cs", // @" ] 7 1 VimBufferTest.cs", // @" ^ 11 1 VimBufferTest.cs", // @" . 7 1 VimBufferTest.cs", // @" < 6 0 VimBufferTest.cs", // @" > 6 1 VimBufferTest.cs", //}; //Assert.Equal(string.Join(Environment.NewLine, expectedMarks), _statusUtil.LastStatus); } } public class ClosingSetsLastEditedPositionMark : VimBufferTest { protected TestableStatusUtil _statusUtil = new TestableStatusUtil(); protected IVimBufferData _vimBufferData; public ClosingSetsLastEditedPositionMark() { OpenFakeVimBufferTestWindow(); _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 0, 0); } protected void OpenFakeVimBufferTestWindow() { OpenFakeVimBufferTestWindow("Hello", "World!"); } protected void OpenFakeVimBufferTestWindow(params string[] lines) { _textView = CreateTextView(lines); _textView.MoveCaretTo(0); _textView.TextBuffer.Properties.AddProperty(Mock.MockVimHost.FileNameKey, "VimBufferTest.cs"); _vimBufferData = CreateVimBufferData(_textView, statusUtil: _statusUtil); _vimBuffer = CreateVimBuffer(_vimBufferData); _vimBuffer.SwitchMode(ModeKind.Command, ModeArgument.None); } protected void AssertPosition(int lineNumber, int column, FSharpOption<VirtualSnapshotPoint> option) { Assert.True(option.IsSome()); var line = VirtualSnapshotPointUtil.GetPoint(option.Value).GetColumn(); Assert.Equal(lineNumber, line.LineNumber); Assert.Equal(column, line.ColumnNumber); } [WpfFact] public void FirstTimeBufferIsZeroZero() { var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } [WpfFact] public void ReopeningTheWindow() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 2, option); } [WpfFact] public void ReopeningTheWindowLastColumn() { _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 0, 5); OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 5, option); } [WpfFact] public void ReopeningTheWindowLastColumnAfterFirstLine() { _vimBuffer.MarkMap.UnloadBuffer(_vimBufferData, "VimBufferTest.cs", 1, 6); OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 6, option); } [WpfFact] public void ReopeningTheWindowLastPositionAtColumnZeroWithLenZeroIsOk() { _textView.SetText("Hello", "", "World!"); _textView.MoveCaretToLine(1, 0); _vimBuffer.Close(); // reopen the file OpenFakeVimBufferTestWindow(); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(1, 0, option); } [WpfFact] public void ReopeningTheWindowWithInvalidColumnLastPositionGoesToZeroZero() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file to invalid column position OpenFakeVimBufferTestWindow("Hello", ""); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } [WpfFact] public void ReopeningTheWindowWithInvalidLineLastPositionGoesToZeroZero() { _textView.MoveCaretToLine(1, 2); _vimBuffer.Close(); // reopen the file to invalid line position OpenFakeVimBufferTestWindow("Hello"); var option = Vim.MarkMap.GetMark(Mark.LastExitedPosition, _vimBuffer.VimBufferData); AssertPosition(0, 0, option); } } public class UnloadedMarksTest : ClosingSetsLastEditedPositionMark { [WpfFact] public void ReloadUnloadedMark() { Vim.MarkMap.SetGlobalMark(Letter.A, _vimBufferData.VimTextBuffer, 1, 2); AssertPosition(1, 2, Vim.MarkMap.GetGlobalMark(Letter.A)); _vimBuffer.Close(); Assert.True(Vim.MarkMap.GetGlobalMark(Letter.A).IsNone()); // reopen the file OpenFakeVimBufferTestWindow(); AssertPosition(1, 2, Vim.MarkMap.GetGlobalMark(Letter.A)); } } public sealed class MiscTest : VimBufferTest { /// <summary> /// Make sure the SwitchdMode event fires when switching modes. /// </summary> [WpfFact] public void SwitchedMode_Event() { var ran = false; _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(ran); } /// <summary> /// Make sure the SwitchdMode event fires even when switching to the /// same mode /// </summary> [WpfFact] public void SwitchedMode_SameModeEvent() { var ran = false; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(ran); } /// <summary> /// Ensure switching to the previous mode operates correctly /// </summary> [WpfFact] public void SwitchPreviousMode_EnterLeaveOrder() { var normal = CreateAndAddNormalMode(); var insert = CreateAndAddInsertMode(); normal.Setup(x => x.OnEnter(ModeArgument.None)).Verifiable(); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); normal.Verify(); normal.Setup(x => x.OnLeave()); insert.Setup(x => x.OnEnter(ModeArgument.None)); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); normal.Verify(); insert.Verify(); insert.Setup(x => x.OnLeave()).Verifiable(); var prev = _vimBuffer.SwitchPreviousMode(); Assert.Same(normal.Object, prev); insert.Verify(); // On tear down all IVimBuffer instances are closed as well as their active // IMode. Need a setup here insert.Setup(x => x.OnClose()); normal.Setup(x => x.OnClose()); } /// <summary> /// SwitchPreviousMode should raise the SwitchedMode event /// </summary> [WpfFact] public void SwitchPreviousMode_RaiseSwitchedMode() { _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); var ran = false; _vimBuffer.SwitchedMode += (s, m) => { ran = true; }; _vimBuffer.SwitchPreviousMode(); Assert.True(ran); } /// <summary> /// When a mode returns the SwitchModeOneTimeCommand value it should cause the /// InOneTimeCommand value to be set /// </summary> [WpfFact] public void SwitchModeOneTimeCommand_SetProperty() { var mode = CreateAndAddInsertMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.NewSwitchModeOneTimeCommand(ModeKind.Normal))); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); _vimBuffer.Process('c'); Assert.True(_vimBuffer.InOneTimeCommand.IsSome(ModeKind.Insert)); } /// <summary> /// Process should handle the return value correctly /// </summary> [WpfFact] public void Process_HandleSwitchPreviousMode() { var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.SwitchPreviousMode)); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('l'); Assert.Equal(ModeKind.Command, _vimBuffer.ModeKind); } /// <summary> /// The nop key shouldn't have any effects /// </summary> [WpfFact] public void Process_Nop() { var old = _vimBuffer.TextSnapshot; foreach (var mode in _vimBuffer.AllModes) { _vimBuffer.SwitchMode(mode.ModeKind, ModeArgument.None); Assert.True(_vimBuffer.Process(VimKey.Nop)); Assert.Equal(old, _vimBuffer.TextSnapshot); } } /// <summary> /// When we are InOneTimeCommand the HandledNeedMoreInput should not cause us to /// do anything with respect to one time command /// </summary> [WpfFact] public void Process_OneTimeCommand_NeedMoreInputDoesNothing() { var mode = CreateAndAddNormalMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.HandledNeedMoreInput); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('c'); Assert.True(_vimBufferRaw.InOneTimeCommand.IsSome(ModeKind.Replace)); } /// <summary> /// Escape should go back to the original mode even if the current IMode doesn't /// support the escape key when we are in a one time command /// </summary> [WpfFact] public void Process_OneTimeCommand_Escape() { var mode = CreateAndAddNormalMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.Error); mode.Setup(x => x.CanProcess(It.IsAny<KeyInput>())).Returns(false); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process(VimKey.Escape); Assert.Equal(ModeKind.Replace, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.IsNone()); } /// <summary> /// When a command is completed in visual mode we shouldn't exit. Else commands like /// 'l' would cause it to exit which is not the Vim behavior /// </summary> [WpfFact] public void Process_OneTimeCommand_VisualMode_Handled() { var mode = CreateAndAddVisualLineMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch)); _vimBuffer.SwitchMode(ModeKind.VisualLine, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('l'); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.Is(ModeKind.Replace)); } /// <summary> /// Switch previous mode should still cause it to go back to the original though /// </summary> [WpfFact] public void Process_OneTimeCommand_VisualMode_SwitchPreviousMode() { var mode = CreateAndAddVisualLineMode(MockBehavior.Loose); mode.Setup(x => x.Process(It.IsAny<KeyInputData>())).Returns(ProcessResult.NewHandled(ModeSwitch.SwitchPreviousMode)); _vimBuffer.SwitchMode(ModeKind.VisualLine, ModeArgument.None); _vimBufferRaw.InOneTimeCommand = FSharpOption.Create(ModeKind.Replace); _vimBuffer.Process('l'); Assert.Equal(ModeKind.Replace, _vimBuffer.ModeKind); Assert.True(_vimBufferRaw.InOneTimeCommand.IsNone()); } /// <summary> /// Processing the buffered key inputs when there are none should have no effect /// </summary> [WpfFact] public void ProcessBufferedKeyInputs_Nothing() { var runCount = 0; _vimBuffer.KeyInputProcessed += delegate { runCount++; }; _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(0, runCount); } /// <summary> /// Processing the buffered key inputs should raise the processed event /// </summary> [WpfFact] public void ProcessBufferedKeyInputs_RaiseProcessed() { var runCount = 0; _textView.SetText(""); _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("cat", "chase the cat", allowRemap: false, KeyRemapMode.Insert); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); _vimBuffer.KeyInputProcessed += delegate { runCount++; }; _vimBuffer.Process("ca"); Assert.Equal(0, runCount); _vimBuffer.ProcessBufferedKeyInputs(); Assert.Equal(2, runCount); Assert.Equal("ca", _textView.GetLine(0).GetText()); } /// <summary> /// Ensure the mode sees the mapped KeyInput value /// </summary> [WpfFact] public void Remap_OneToOne() { _localKeyMap.AddKeyMapping("a", "l", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// When a single key is mapped to multiple both need to be passed onto the /// IMode instance /// </summary> [WpfFact] public void Remap_OneToMany() { _localKeyMap.AddKeyMapping("a", "dw", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Don't use mappings for the wrong IMode /// </summary> [WpfFact] public void Remap_WrongMode() { _localKeyMap.AddKeyMapping("l", "dw", allowRemap: false, KeyRemapMode.Insert); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('l'); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// When INormalMode is in OperatorPending we need to use operating pending /// remapping /// </summary> [WpfFact] public void Remap_OperatorPending() { _localKeyMap.AddKeyMapping("z", "w", allowRemap: false, KeyRemapMode.OperatorPending); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("d"); Assert.Equal(_vimBuffer.NormalMode.KeyRemapMode, KeyRemapMode.OperatorPending); _vimBuffer.Process("z"); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Recursive mappings should print out an error message when used /// </summary> [WpfFact] public void Remap_Recursive() { _localKeyMap.AddKeyMapping("a", "b", allowRemap: true, KeyRemapMode.Normal); _localKeyMap.AddKeyMapping("b", "a", allowRemap: true, KeyRemapMode.Normal); var didRun = false; _vimBuffer.ErrorMessage += (notUsed, args) => { Assert.Equal(Resources.Vim_RecursiveMapping, args.Message); didRun = true; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process('a'); Assert.True(didRun); } /// <summary> /// When we buffer input and fail to find a mapping every KeyInput value /// should be passed to the IMode /// </summary> [WpfFact] public void Remap_BufferedFailed() { _localKeyMap.AddKeyMapping("do", "cat", allowRemap: false, KeyRemapMode.Normal); _textView.SetText("cat dog", 0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _vimBuffer.Process("d"); Assert.Equal('d', _vimBuffer.BufferedKeyInputs.Head.Char); _vimBuffer.Process("w"); Assert.Equal("dog", _textView.GetLine(0).GetText()); } /// <summary> /// Make sure the KeyInput is passed down to the IMode /// </summary> [WpfFact] public void CanProcess_Simple() { var keyInput = KeyInputUtil.CharToKeyInput('c'); var normal = CreateAndAddNormalMode(MockBehavior.Loose); normal.Setup(x => x.CanProcess(keyInput)).Returns(true).Verifiable(); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(_vimBuffer.CanProcess(keyInput)); normal.Verify(); } /// <summary> /// Make sure the mapped KeyInput is passed down to the IMode /// </summary> [WpfFact] public void CanProcess_Mapped() { _localKeyMap.AddKeyMapping("a", "c", allowRemap: true, KeyRemapMode.Normal);
VsVim/VsVim
11fe6cbbbabfab3653f0d63cdf33ec1976aab592
Format code (review feedback)
diff --git a/Src/VimCore/CommandUtil.fs b/Src/VimCore/CommandUtil.fs index 78f2639..bd6c97f 100644 --- a/Src/VimCore/CommandUtil.fs +++ b/Src/VimCore/CommandUtil.fs @@ -1,694 +1,694 @@ #light namespace Vim open Vim.Modes open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Operations open Microsoft.VisualStudio.Text.Editor open Microsoft.VisualStudio.Text.Outlining open Microsoft.VisualStudio.Text.Formatting open System.Text open RegexPatternUtil open VimCoreExtensions open ITextEditExtensions open StringBuilderExtensions [<RequireQualifiedAccess>] [<NoComparison>] [<StructuralEquality>] type internal NumberValue = | Decimal of Decimal: int64 | Octal of Octal: uint64 | Hex of Hex: uint64 | Binary of Binary: uint64 | Alpha of Alpha: char with member x.NumberFormat = match x with | Decimal _ -> NumberFormat.Decimal | Octal _ -> NumberFormat.Octal | Hex _ -> NumberFormat.Hex | Binary _ -> NumberFormat.Binary | Alpha _ -> NumberFormat.Alpha /// There are some commands which if began in normal mode must end in normal /// mode (undo and redo). In general this is easy, don't switch modes. But often /// the code needs to call out to 3rd party code which can change the mode by /// altering the selection. /// /// This is a simple IDisposable type which will put us back into normal mode /// if this happens. type internal NormalModeSelectionGuard ( _vimBufferData: IVimBufferData ) = let _beganInNormalMode = _vimBufferData.VimTextBuffer.ModeKind = ModeKind.Normal member x.Dispose() = let selection = _vimBufferData.TextView.Selection if _beganInNormalMode && not selection.IsEmpty then TextViewUtil.ClearSelection _vimBufferData.TextView _vimBufferData.VimTextBuffer.SwitchMode ModeKind.Normal ModeArgument.None |> ignore interface System.IDisposable with member x.Dispose() = x.Dispose() /// This type houses the functionality behind a large set of the available /// Vim commands. /// /// This type could be further broken down into 2-3 types (one util to support /// the commands for specific modes). But there is a lot of benefit to keeping /// them together as it reduces the overhead of sharing common infrastructure. /// /// I've debated back and forth about separating them out. Thus far though I've /// decided to keep them all together because while there is a large set of /// functionality here there is very little state. So long as I can keep the /// amount of stored state low here I believe it counters the size of the type type internal CommandUtil ( _vimBufferData: IVimBufferData, _motionUtil: IMotionUtil, _commonOperations: ICommonOperations, _foldManager: IFoldManager, _insertUtil: IInsertUtil, _bulkOperations: IBulkOperations, _lineChangeTracker: ILineChangeTracker ) = let _vimTextBuffer = _vimBufferData.VimTextBuffer let _wordUtil = _vimBufferData.WordUtil let _wordNavigator = _vimTextBuffer.WordNavigator let _textView = _vimBufferData.TextView let _textBuffer = _textView.TextBuffer let _bufferGraph = _textView.BufferGraph let _statusUtil = _vimBufferData.StatusUtil let _undoRedoOperations = _vimBufferData.UndoRedoOperations let _localSettings = _vimBufferData.LocalSettings let _windowSettings = _vimBufferData.WindowSettings let _globalSettings = _localSettings.GlobalSettings let _vim = _vimBufferData.Vim let _vimData = _vim.VimData let _vimHost = _vim.VimHost let _markMap = _vim.MarkMap let _registerMap = _vim.RegisterMap let _searchService = _vim.SearchService let _macroRecorder = _vim.MacroRecorder let _jumpList = _vimBufferData.JumpList let _editorOperations = _commonOperations.EditorOperations let _options = _commonOperations.EditorOptions let mutable _inRepeatLastChange = false /// The last mouse down position before it was adjusted for virtual edit let mutable _leftMouseDownPoint: VirtualSnapshotPoint option = None /// Whether to select by word when dragging the mouse let mutable _doSelectByWord = false /// The SnapshotPoint for the caret member x.CaretPoint = TextViewUtil.GetCaretPoint _textView /// The VirtualSnapshotPoint for the caret member x.CaretVirtualPoint = TextViewUtil.GetCaretVirtualPoint _textView /// The column of the caret member x.CaretColumn = TextViewUtil.GetCaretColumn _textView /// The virtual column of the caret member x.CaretVirtualColumn = VirtualSnapshotColumn(x.CaretVirtualPoint) /// The ITextSnapshotLine for the caret member x.CaretLine = TextViewUtil.GetCaretLine _textView /// The line number for the caret member x.CaretLineNumber = x.CaretLine.LineNumber /// The SnapshotLineRange for the caret line member x.CaretLineRange = x.CaretLine |> SnapshotLineRangeUtil.CreateForLine /// The SnapshotPoint and ITextSnapshotLine for the caret member x.CaretPointAndLine = TextViewUtil.GetCaretPointAndLine _textView /// The current ITextSnapshot instance for the ITextBuffer member x.CurrentSnapshot = _textBuffer.CurrentSnapshot /// Add a new caret at the mouse point member x.AddCaretAtMousePoint () = _commonOperations.AddCaretAtMousePoint() CommandResult.Completed ModeSwitch.NoSwitch /// Add a new caret on an adjacent line in the specified direction member x.AddCaretOnAdjacentLine direction = _commonOperations.AddCaretOrSelectionOnAdjacentLine direction CommandResult.Completed ModeSwitch.NoSwitch /// Add a new selection on an adjacent line in the specified direction member x.AddSelectionOnAdjacentLine direction = _commonOperations.AddCaretOrSelectionOnAdjacentLine direction CommandResult.Completed ModeSwitch.NoSwitch /// Add count values to the specific word member x.AddToWord count = match x.AddToWordAtPointInSpan x.CaretPoint x.CaretLine.Extent count with | Some (span, text) -> // Need a transaction here in order to properly position the caret. // After the add the caret needs to be positioned on the last // character in the number. x.EditWithUndoTransaction "Add to word" (fun () -> _textBuffer.Replace(span.Span, text) |> ignore let position = span.Start.Position + text.Length - 1 TextViewUtil.MoveCaretToPosition _textView position) | None -> _commonOperations.Beep() CommandResult.Completed ModeSwitch.NoSwitch /// Add count to the word in each line of the selection, optionally progressively member x.AddToSelection (visualSpan: VisualSpan) count isProgressive = let startPoint = visualSpan.Start // Use a transaction to guarantee caret position. Caret should be at // the start during undo and redo so move it before the edit TextViewUtil.MoveCaretToPoint _textView startPoint x.EditWithUndoTransaction "Add to selection" (fun () -> use edit = _textBuffer.CreateEdit() - let AddToWordAtPointInSpanAndIncrementIndex index (span:SnapshotSpan) = + let AddToWordAtPointInSpanAndIncrementIndex index (span: SnapshotSpan) = let countForIndex = if isProgressive then count * (index + 1) else count match x.AddToWordAtPointInSpan span.Start span countForIndex with | Some (span, text) -> edit.Replace(span.Span, text) |> ignore index + 1 | None -> index Seq.fold AddToWordAtPointInSpanAndIncrementIndex 0 visualSpan.PerLineSpans |> ignore let position = x.ApplyEditAndMapPosition edit startPoint.Position TextViewUtil.MoveCaretToPosition _textView position) CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Add count values to the specific word member x.AddToWordAtPointInSpan point span count: (SnapshotSpan * string) option = match x.GetNumberAtPointInSpan point span with | Some (numberValue, span) -> // Calculate the new value of the number. let numberText = span.GetText() let text = match numberValue with | NumberValue.Alpha c -> c |> CharUtil.AlphaAdd count |> StringUtil.OfChar | NumberValue.Decimal number -> let newNumber = number + int64(count) let width = if numberText.StartsWith("-0") || numberText.StartsWith("0") then let oldSignWidth = if numberText.StartsWith("-") then 1 else 0 let newSignWidth = if newNumber < 0L then 1 else 0 numberText.Length + newSignWidth - oldSignWidth else 1 sprintf "%0*d" width newNumber | NumberValue.Octal number -> let newNumber = number + uint64(count) sprintf "0%0*o" (numberText.Length - 1) newNumber | NumberValue.Hex number -> let prefix = numberText.Substring(0, 2) let width = numberText.Length - 2 let newNumber = number + uint64(count) // If the number has any uppercase digits, use uppercase // for the new number. if RegularExpressions.Regex.Match(numberText, @"[A-F]").Success then sprintf "%s%0*X" prefix width newNumber else sprintf "%s%0*x" prefix width newNumber | NumberValue.Binary number -> let prefix = numberText.Substring(0, 2) let width = numberText.Length - 2 let newNumber = number + uint64(count) // There are no overloads for unsigned integer types and // binary convert is always unsigned anyway. let formattedNumber = System.Convert.ToString(int64(newNumber), 2) prefix + formattedNumber.PadLeft(width, '0') Some (span, text) | None -> None /// Apply the ITextEdit and returned the mapped position value from the resulting /// ITextSnapshot into the current ITextSnapshot. /// /// A number of commands will edit the text and calculate the position of the caret /// based on the edits about to be made. It's possible for other extensions to listen /// to the events fired by an edit and make fix up edits. This code accounts for that /// and returns the position mapped into the current ITextSnapshot member x.ApplyEditAndMapPoint (textEdit: ITextEdit) position = let editSnapshot = textEdit.Apply() SnapshotPoint(editSnapshot, position) |> _commonOperations.MapPointNegativeToCurrentSnapshot member x.ApplyEditAndMapColumn (textEdit: ITextEdit) position = let point = x.ApplyEditAndMapPoint textEdit position SnapshotColumn(point) member x.ApplyEditAndMapPosition (textEdit: ITextEdit) position = let point = x.ApplyEditAndMapPoint textEdit position point.Position /// Calculate the new RegisterValue for the provided one for put with indent /// operations. member x.CalculateIdentStringData (registerValue: RegisterValue) = // Get the indent string to apply to the lines which are indented let indent = x.CaretLine |> SnapshotLineUtil.GetIndentText |> (fun text -> _commonOperations.NormalizeBlanks text 0) // Adjust the indentation on a given line of text to have the indentation // previously calculated let adjustTextLine (textLine: TextLine) = let oldIndent = textLine.Text |> Seq.takeWhile CharUtil.IsBlank |> StringUtil.OfCharSeq let text = indent + (textLine.Text.Substring(oldIndent.Length)) { textLine with Text = text } // Really a put after with indent is just a normal put after of the adjusted // register value. So adjust here and forward on the magic let stringData = let stringData = registerValue.StringData match stringData with | StringData.Block _ -> // Block values don't participate in indentation of this manner stringData | StringData.Simple text -> match registerValue.OperationKind with | OperationKind.CharacterWise -> // We only change lines after the first. So break it into separate lines // fix their indent and then produce the new value. let lines = TextLine.GetTextLines text let head = lines.Head let rest = lines.Rest |> Seq.map adjustTextLine let text = let all = Seq.append (Seq.singleton head) rest TextLine.CreateString all StringData.Simple text | OperationKind.LineWise -> // Change every line for a line wise operation text |> TextLine.GetTextLines |> Seq.map adjustTextLine |> TextLine.CreateString |> StringData.Simple x.CreateRegisterValue stringData registerValue.OperationKind /// Calculate the VisualSpan value for the associated ITextBuffer given the /// StoreVisualSpan value member x.CalculateVisualSpan stored = match stored with | StoredVisualSpan.Line (Count = count) -> // Repeating a LineWise operation just creates a span with the same // number of lines as the original operation let range = SnapshotLineRangeUtil.CreateForLineAndMaxCount x.CaretLine count VisualSpan.Line range | StoredVisualSpan.Character (LineCount = lineCount; LastLineMaxPositionCount = lastLineMaxPositionCount) -> let characterSpan = CharacterSpan(x.CaretPoint, lineCount, lastLineMaxPositionCount) VisualSpan.Character characterSpan | StoredVisualSpan.Block (Width = width; Height = height; EndOfLine = endOfLine) -> // Need to rehydrate spans of length 'length' on 'count' lines from the // current caret position let blockSpan = BlockSpan(x.CaretVirtualPoint, _localSettings.TabStop, width, height, endOfLine) VisualSpan.Block blockSpan member x.CalculateDeleteOperation (result: MotionResult) = if Util.IsFlagSet result.MotionResultFlags MotionResultFlags.BigDelete then RegisterOperation.BigDelete else RegisterOperation.Delete member x.CancelOperation () = x.ClearSecondarySelections() _vimTextBuffer.SwitchMode ModeKind.Normal ModeArgument.CancelOperation CommandResult.Completed ModeSwitch.NoSwitch /// Change the characters in the given span via the specified change kind member x.ChangeCaseSpanCore kind (editSpan: EditSpan) = let func = match kind with | ChangeCharacterKind.Rot13 -> CharUtil.ChangeRot13 | ChangeCharacterKind.ToLowerCase -> CharUtil.ToLower | ChangeCharacterKind.ToUpperCase -> CharUtil.ToUpper | ChangeCharacterKind.ToggleCase -> CharUtil.ChangeCase use edit = _textBuffer.CreateEdit() editSpan.Spans |> Seq.map (SnapshotSpanUtil.GetPoints SearchPath.Forward) |> Seq.concat |> Seq.filter (fun p -> CharUtil.IsLetter (p.GetChar())) |> Seq.iter (fun p -> let change = func (p.GetChar()) |> StringUtil.OfChar edit.Replace(p.Position, 1, change) |> ignore) edit.Apply() |> ignore /// Change the caret line via the specified ChangeCharacterKind. member x.ChangeCaseCaretLine kind = // The caret should be positioned on the first non-blank space in // the line. If the line is completely blank the caret should // not be moved. Caret should be in the same place for undo / redo // so move before and inside the transaction let position = x.CaretLine |> SnapshotLineUtil.GetPoints SearchPath.Forward |> Seq.skipWhile SnapshotPointUtil.IsWhiteSpace |> Seq.map SnapshotPointUtil.GetPosition |> SeqUtil.tryHeadOnly let maybeMoveCaret () = match position with | Some position -> TextViewUtil.MoveCaretToPosition _textView position | None -> () maybeMoveCaret() x.EditWithUndoTransaction "Change" (fun () -> x.ChangeCaseSpanCore kind (EditSpan.Single (SnapshotColumnSpan(x.CaretLine))) maybeMoveCaret()) CommandResult.Completed ModeSwitch.NoSwitch /// Change the case of the specified motion member x.ChangeCaseMotion kind (result: MotionResult) = // The caret should be placed at the start of the motion for both // undo / redo so move before and inside the transaction TextViewUtil.MoveCaretToPoint _textView result.Span.Start x.EditWithUndoTransaction "Change" (fun () -> x.ChangeCaseSpanCore kind result.EditSpan TextViewUtil.MoveCaretToPosition _textView result.Span.Start.Position) CommandResult.Completed ModeSwitch.NoSwitch /// Change the case of the current caret point member x.ChangeCaseCaretPoint kind count = // The caret should be placed after the caret point but only // for redo. Undo should move back to the current position so // don't move until inside the transaction x.EditWithUndoTransaction "Change" (fun () -> let span = let endColumn = x.CaretColumn.AddInLineOrEnd(count) SnapshotColumnSpan(x.CaretColumn, endColumn) let editSpan = EditSpan.Single span x.ChangeCaseSpanCore kind editSpan // Move the caret but make sure to respect the 'virtualedit' option let point = SnapshotPoint(x.CurrentSnapshot, span.End.StartPosition) _commonOperations.MoveCaretToPoint point ViewFlags.VirtualEdit) CommandResult.Completed ModeSwitch.NoSwitch /// Change the case of the selected text. member x.ChangeCaseVisual kind (visualSpan: VisualSpan) = // The caret should be positioned at the start of the VisualSpan for both // undo / redo so move it before and inside the transaction let point = visualSpan.Start let moveCaret () = TextViewUtil.MoveCaretToPosition _textView point.Position moveCaret() x.EditWithUndoTransaction "Change" (fun () -> x.ChangeCaseSpanCore kind visualSpan.EditSpan moveCaret()) CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Delete the specified motion and enter insert mode member x.ChangeMotion registerName (result: MotionResult) = // This command has legacy / special case behavior for forward word motions. It will // not delete any trailing whitespace in the span if the motion is created for a forward // word motion. This behavior is detailed in the :help WORD section of the gVim // documentation and is likely legacy behavior coming from the original vi // implementation. A larger discussion thread is available here // http://groups.google.com/group/vim_use/browse_thread/thread/88b6499bbcb0878d/561dfe13d3f2ef63?lnk=gst&q=whitespace+cw#561dfe13d3f2ef63 let span = if result.IsAnyWordMotion && result.IsForward then let point = result.Span |> SnapshotSpanUtil.GetPoints SearchPath.Backward |> Seq.tryFind (fun x -> x.GetChar() |> CharUtil.IsWhiteSpace |> not) match point with | Some(p) -> let endPoint = p |> SnapshotPointUtil.TryAddOne |> OptionUtil.getOrDefault (SnapshotUtil.GetEndPoint (p.Snapshot)) SnapshotSpan(result.Span.Start, endPoint) | None -> result.Span elif result.OperationKind = OperationKind.LineWise then // If the change command ends inside a line break then the actual delete operation // is backed up so that it leaves a single blank line after the delete operation. This // allows the insert to begin on a blank line match SnapshotSpanUtil.GetLastIncludedPoint result.Span with | Some point -> if SnapshotPointUtil.IsInsideLineBreak point then let line = SnapshotPointUtil.GetContainingLine point SnapshotSpan(result.Span.Start, line.End) else result.Span | None -> result.Span else result.Span // Use an undo transaction to preserve the caret position. Experiments show that the rules // for caret undo should be // 1. start of the change if motion is character wise // 2. start of second line if motion is line wise let point = match result.MotionKind with | MotionKind.CharacterWiseExclusive -> span.Start | MotionKind.CharacterWiseInclusive -> span.Start | MotionKind.LineWise -> let startLine = SnapshotSpanUtil.GetStartLine span let line = SnapshotUtil.TryGetLine span.Snapshot (startLine.LineNumber + 1) |> OptionUtil.getOrDefault startLine line.Start TextViewUtil.MoveCaretToPoint _textView point let commandResult = x.EditWithLinkedChange "Change" (fun () -> let savedStartLine = SnapshotPointUtil.GetContainingLine span.Start _textBuffer.Delete(span.Span) |> ignore if result.MotionKind = MotionKind.LineWise then SnapshotUtil.GetLine x.CurrentSnapshot savedStartLine.LineNumber |> x.MoveCaretToNewLineIndent savedStartLine else span.Start.TranslateTo(_textBuffer.CurrentSnapshot, PointTrackingMode.Negative) |> TextViewUtil.MoveCaretToPoint _textView) // Now that the delete is complete update the register let value = x.CreateRegisterValue (StringData.OfSpan span) result.OperationKind let operation = x.CalculateDeleteOperation result _commonOperations.SetRegisterValue registerName operation value commandResult /// Delete 'count' lines and begin insert mode. The documentation of this command /// and behavior are a bit off. It's documented like it behaves like 'dd + insert mode' /// but behaves more like ChangeTillEndOfLine but linewise and deletes the entire /// first line member x.ChangeLines count registerName = let range = SnapshotLineRangeUtil.CreateForLineAndMaxCount x.CaretLine count x.ChangeLinesCore range registerName /// Core routine for changing a set of lines in the ITextBuffer. This is the backing function /// for changing lines in both normal and visual mode member x.ChangeLinesCore (range: SnapshotLineRange) registerName = // Caret position for the undo operation depends on the number of lines which are in // range being deleted. If there is a single line then we position it before the first // non space / tab character in the first line. If there is more than one line then we // position it at the equivalent location in the second line. // // There appears to be no logical reason for this behavior difference but it exists let savedStartLine = range.StartLine let point = let line = if range.Count = 1 then range.StartLine else SnapshotUtil.GetLine range.Snapshot (range.StartLineNumber + 1) line |> SnapshotLineUtil.GetPoints SearchPath.Forward |> Seq.skipWhile SnapshotPointUtil.IsBlank |> SeqUtil.tryHeadOnly match point with | None -> () | Some point -> TextViewUtil.MoveCaretToPoint _textView point // Start an edit transaction to get the appropriate undo / redo behavior for the // caret movement after the edit. x.EditWithLinkedChange "ChangeLines" (fun () -> // Actually delete the text and position the caret _textBuffer.Delete(range.Extent.Span) |> ignore let line = SnapshotUtil.GetLine x.CurrentSnapshot savedStartLine.LineNumber x.MoveCaretToNewLineIndent savedStartLine line // Update the register now that the operation is complete. Register value is odd here // because we really didn't delete linewise but it's required to be a linewise // operation. let stringData = range.Extent.GetText() |> StringData.Simple let value = x.CreateRegisterValue stringData OperationKind.LineWise _commonOperations.SetRegisterValue registerName RegisterOperation.Delete value) /// Delete the selected lines and begin insert mode (implements the 'S', 'C' and 'R' visual /// mode commands. This is very similar to DeleteLineSelection except that block deletion /// can be special cased depending on the command it's used in member x.ChangeLineSelection registerName (visualSpan: VisualSpan) specialCaseBlock = // The majority of cases simply delete a SnapshotLineRange directly. Handle that here let deleteRange (range: SnapshotLineRange) = // In an undo the caret position has 2 cases. // - Single line range: Start of the first line // - Multiline range: Start of the second line. let savedStartLine = range.StartLine let point = if range.Count = 1 then range.StartLine.Start else let next = SnapshotUtil.GetLine range.Snapshot (range.StartLineNumber + 1) next.Start TextViewUtil.MoveCaretToPoint _textView point let commandResult = x.EditWithLinkedChange "ChangeLines" (fun () -> _textBuffer.Delete(range.Extent.Span) |> ignore let line = SnapshotUtil.GetLine x.CurrentSnapshot savedStartLine.LineNumber x.MoveCaretToNewLineIndent savedStartLine line) (EditSpan.Single range.ColumnExtent, commandResult) // The special casing of block deletion is handled here let deleteBlock (col: NonEmptyCollection<SnapshotOverlapColumnSpan>) = // First step is to change the SnapshotSpan instances to extent from the start to the // end of the current line let col = col |> NonEmptyCollectionUtil.Map (fun span -> let endColumn = let endColumn = SnapshotColumn.GetLineEnd(span.Start.Line) SnapshotOverlapColumn(endColumn, _localSettings.TabStop) SnapshotOverlapColumnSpan(span.Start, endColumn, _localSettings.TabStop)) // Caret should be positioned at the start of the span for undo TextViewUtil.MoveCaretToPoint _textView col.Head.Start.Column.StartPoint let commandResult = x.EditWithLinkedChange "ChangeLines" (fun () -> let edit = _textBuffer.CreateEdit() col |> Seq.iter (fun span -> edit.Delete(span) |> ignore) let position = x.ApplyEditAndMapPosition edit col.Head.Start.Column.StartPosition TextViewUtil.MoveCaretToPosition _textView position) (EditSpan.Block col, commandResult) // Dispatch to the appropriate type of edit let editSpan, commandResult = match visualSpan with | VisualSpan.Character characterSpan -> characterSpan.Span |> SnapshotLineRangeUtil.CreateForSpan |> deleteRange | VisualSpan.Line range -> deleteRange range | VisualSpan.Block blockSpan -> if specialCaseBlock then deleteBlock blockSpan.BlockOverlapColumnSpans else visualSpan.EditSpan.OverarchingSpan |> SnapshotLineRangeUtil.CreateForSpan |> deleteRange let value = x.CreateRegisterValue (StringData.OfEditSpan editSpan) OperationKind.LineWise _commonOperations.SetRegisterValue registerName RegisterOperation.Delete value commandResult /// Delete till the end of the line and start insert mode member x.ChangeTillEndOfLine count registerName = // The actual text edit portion of this operation is identical to the // DeleteTillEndOfLine operation. There is a difference though in the // positioning of the caret. DeleteTillEndOfLine needs to consider the virtual // space settings since it remains in normal mode but change does not due // to it switching to insert mode let caretPosition = x.CaretPoint.Position x.EditWithLinkedChange "ChangeTillEndOfLine" (fun () -> x.DeleteTillEndOfLineCore count registerName // Move the caret back to it's original position. Don't consider virtual // space here since we're switching to insert mode let point = SnapshotPoint(x.CurrentSnapshot, caretPosition) _commonOperations.MoveCaretToPoint point ViewFlags.None) /// Delete the selected text in Visual Mode and begin insert mode with a linked /// transaction. member x.ChangeSelection registerName (visualSpan: VisualSpan) = match visualSpan with | VisualSpan.Character _ -> // For block and character modes the change selection command is simply a // delete of the span and move into insert mode. // // Caret needs to be positioned at the front of the span in undo so move it // before we create the transaction TextViewUtil.MoveCaretToPoint _textView visualSpan.Start x.EditWithLinkedChange "ChangeSelection" (fun() -> x.DeleteSelection registerName visualSpan |> ignore) | VisualSpan.Block blockSpan -> // Change in block mode has behavior very similar to Shift + Insert. It needs // to be a change followed by a transition into insert where the insert actions // are repeated across the block span // Caret needs to be positioned at the front of the span in undo so move it // before we create the transaction TextViewUtil.MoveCaretToPoint _textView visualSpan.Start x.EditBlockWithLinkedChange "Change Block" blockSpan VisualInsertKind.Start (fun () -> x.DeleteSelection registerName visualSpan |> ignore) | VisualSpan.Line range -> x.ChangeLinesCore range registerName /// Close a single fold under the caret member x.CloseFoldInSelection (visualSpan: VisualSpan) = let range = visualSpan.LineRange let offset = range.StartLineNumber for i = 0 to range.Count - 1 do let line = SnapshotUtil.GetLine x.CurrentSnapshot (offset + i) _foldManager.CloseFold line.Start 1 CommandResult.Completed ModeSwitch.NoSwitch /// Close 'count' folds under the caret member x.CloseFoldUnderCaret count = _foldManager.CloseFold x.CaretPoint count CommandResult.Completed ModeSwitch.NoSwitch /// Close all of the folds in the buffer
VsVim/VsVim
63637fa16b87e154813e803647d84cd6af8a5a6d
Restore caret when using system copy after yank
diff --git a/Src/VimCore/CommonOperations.fs b/Src/VimCore/CommonOperations.fs index aa2baf5..b45e658 100644 --- a/Src/VimCore/CommonOperations.fs +++ b/Src/VimCore/CommonOperations.fs @@ -1708,1028 +1708,1032 @@ type internal CommonOperations let key = extractKey keyPattern line match key with | "" -> defaultValue | _ -> try Convert.ToDouble(key) with | _ -> defaultValue // Precompile the regular expression. let getKeyFunction (keyPattern: string) = parseFloat (new Regex(keyPattern)) // Given a text line, extract a float key. let floatPattern = @"[-+]?([0-9]*\.?[0-9]+|[0-9]+\.)([eE][-+]?[0-9]+)?" let keyFunction = getKeyFunction floatPattern sortByFunction keyFunction lines else // Given a text line, extract a text key. let keyFunction = if Util.IsFlagSet flags SortFlags.IgnoreCase then projectLine >> toLower else projectLine sortByFunction keyFunction lines // Optionally filter out duplicates. let sortedLines = if Util.IsFlagSet flags SortFlags.Unique then if Util.IsFlagSet flags SortFlags.IgnoreCase then sortedLines |> Seq.distinctBy toLower else sortedLines |> Seq.distinct else sortedLines // Concatenate the sorted lines. let newLine = EditUtil.NewLine _editorOptions _textBuffer let replacement = sortedLines |> String.concat newLine // Replace the old lines with the sorted lines. _textBuffer.Replace(range.Extent.Span, replacement) |> ignore // Place the cursor on the first non-blank character of the first line sorted. let firstLine = SnapshotUtil.GetLine _textView.TextSnapshot range.StartLineNumber TextViewUtil.MoveCaretToPoint _textView firstLine.Start _editorOperations.MoveToStartOfLineAfterWhiteSpace(false) /// Perform a regular expression substitution within the specified regions member x.SubstituteCore (regex: VimRegex) (replace: string) (flags: SubstituteFlags) (searchSpan: SnapshotSpan) (replacementSpan: SnapshotSpan) = // This is complicated by the fact that vim allows patterns to // start within the line range but extend arbitarily far beyond // it into the buffer. So we have two concepts in play here: // - search region: The valid region for the search to start in // - replacement region: The valid region for the search to end in // Both regions should always start at same place. For normal // (non-multiline) patterns, the two regions can be the same. // For multiline patterns, the second region should extend to // the end of the buffer. let snapshot = _textView.TextSnapshot; // Use an edit to apply all the changes at once after // we've found all the matches. use edit = _textView.TextBuffer.CreateEdit() // The start and end position delineate the bounds of the search region. let startPosition = searchSpan.Start.Position let endPosition = searchSpan.End.Position let replacementRegion = replacementSpan.GetText() let lastLineHasNoLineBreak = not (SnapshotUtil.AllLinesHaveLineBreaks snapshot) // The following code assumes we can use indexes arising from // the replacement region string as offsets into the snapshot. Contract.Assert(replacementRegion.Length = replacementSpan.Length) // Get a snapshot line corresponding to a replacement region index. let getLineForIndex (index: int) = new SnapshotPoint(snapshot, startPosition + index) |> SnapshotPointUtil.GetContainingLine // Does the match start within the specified limits? let isMatchValid (capture: Match) = if capture.Success then let index = capture.Index let length = endPosition - startPosition // We can only match at the very end of the search // region if the last line doesn't have a linebreak // and we're at the end of the buffer. if index < length || (index = length && lastLineHasNoLineBreak && index = snapshot.Length) then if regex.MatchesVisualSelection then // If the pattern includes '\%V', we need to check the match // against the last visual selection. let visualSelection = _vimTextBuffer.LastVisualSelection match visualSelection with | None -> false | Some visualSelection -> // Is the match entirely within the visual selection? let selectionStartIndex = visualSelection.VisualSpan.Start.Position - startPosition let selectionEndIndex = visualSelection.VisualSpan.End.Position - startPosition index >= selectionStartIndex && index + capture.Length <= selectionEndIndex else true else false else false // Get a snapshot span corresponding to a regex match. let getSpanforCapture (capture: Match) = let matchStartPosition = startPosition + capture.Index let matchLength = capture.Length new SnapshotSpan(snapshot, matchStartPosition, matchLength) // Replace one match. let replaceOne (capture: Match) = let matchSpan = getSpanforCapture capture // Get the new text to replace the match span with. let newText = if Util.IsFlagSet flags SubstituteFlags.LiteralReplacement then replace else let replaceData = x.GetReplaceData x.CaretPoint let oldText = matchSpan.GetText() regex.Replace oldText replace replaceData _registerMap // Perform the replacement. edit.Replace(matchSpan.Span, newText) |> ignore // Update the status for the substitute operation let printMessage (matches: ITextSnapshotLine list) = // Get the replace message for multiple lines. let replaceMessage = let replaceCount = matches.Length let lineCount = matches |> Seq.distinctBy (fun line -> line.LineNumber) |> Seq.length if replaceCount > 1 then Resources.Common_SubstituteComplete replaceCount lineCount |> Some else None let printReplaceMessage () = match replaceMessage with | None -> () | Some(msg) -> _statusUtil.OnStatus msg // Find the last line in the replace sequence. This is printed out to the // user and needs to represent the current state of the line, not the previous let lastLine = if Seq.isEmpty matches then None else let line = matches |> SeqUtil.last let span = line.ExtentIncludingLineBreak let tracking = span.Snapshot.CreateTrackingSpan(span.Span, SpanTrackingMode.EdgeInclusive) match TrackingSpanUtil.GetSpan _textView.TextSnapshot tracking with | None -> None | Some(span) -> SnapshotSpanUtil.GetStartLine span |> Some // Now consider the options. match lastLine with | None -> printReplaceMessage() | Some(line) -> let printBoth msg = match replaceMessage with | None -> _statusUtil.OnStatus msg | Some(replaceMessage) -> _statusUtil.OnStatusLong [replaceMessage; msg] if Util.IsFlagSet flags SubstituteFlags.PrintLast then printBoth (line.GetText()) elif Util.IsFlagSet flags SubstituteFlags.PrintLastWithNumber then sprintf " %d %s" (line.LineNumber+1) (line.GetText()) |> printBoth elif Util.IsFlagSet flags SubstituteFlags.PrintLastWithList then sprintf "%s$" (line.GetText()) |> printBoth else printReplaceMessage() // Get all the matches in the replacement region. let matches = regex.Regex.Matches(replacementRegion) |> Seq.cast<Match> |> Seq.filter isMatchValid |> Seq.map (fun capture -> (capture, getLineForIndex capture.Index)) |> Seq.toList // Obey the 'replace all' flag by using only the first // match from each line group. let matches = if Util.IsFlagSet flags SubstituteFlags.ReplaceAll then matches else matches |> Seq.groupBy (fun (_, line) -> line.LineNumber) |> Seq.map (fun (lineNumber, group) -> Seq.head group) |> Seq.toList // Actually do the replace unless the 'report only' flag was specified. if not (Util.IsFlagSet flags SubstituteFlags.ReportOnly) then matches |> Seq.iter (fun (capture, _) -> replaceOne capture) // Discard the capture information. let matches = matches |> Seq.map (fun (_, line) -> line) |> Seq.toList if edit.HasEffectiveChanges then edit.Apply() |> ignore printMessage matches elif Util.IsFlagSet flags SubstituteFlags.ReportOnly then edit.Cancel() printMessage matches elif Util.IsFlagSet flags SubstituteFlags.SuppressError then edit.Cancel() else edit.Cancel() _statusUtil.OnError (Resources.Common_PatternNotFound regex.VimPattern) /// Perform a pattern substitution on the specifed line range member x.Substitute (pattern: string) (replace: string) (range: SnapshotLineRange) (flags: SubstituteFlags) = match VimRegexFactory.CreateForSubstituteFlags pattern _globalSettings flags with | None -> _statusUtil.OnError (Resources.Common_PatternNotFound pattern) | Some regex -> let snapshot = _textView.TextSnapshot; // The beginning of a match can occur within the search region. let searchSpan = range.ExtentIncludingLineBreak // The end of the match can occur within the replacement region. let replacementSpan = if regex.IncludesNewLine then // Grow the replacement span to the end of the // buffer if the regex could match a newline. new SnapshotSpan(searchSpan.Start, SnapshotUtil.GetEndPoint snapshot) else range.ExtentIncludingLineBreak // Check for expression replace (see vim ':help :s\='). if replace.StartsWith(@"\=") then let expressionText = replace.Substring(2) let vim = _vimBufferData.Vim match vim.TryGetVimBuffer _textView with | true, vimBuffer -> let vimInterpreter = vim.GetVimInterpreter vimBuffer match vimInterpreter.EvaluateExpression expressionText with | EvaluateResult.Succeeded variableValue -> let replace = variableValue.StringValue let flags = flags ||| SubstituteFlags.LiteralReplacement x.SubstituteCore regex replace flags searchSpan replacementSpan | EvaluateResult.Failed message -> _statusUtil.OnError message | _ -> _statusUtil.OnError Resources.Parser_InvalidArgument else x.SubstituteCore regex replace flags searchSpan replacementSpan // Make sure to update the saved state. Note that there are 2 patterns stored // across buffers. // // 1. Last substituted pattern // 2. Last searched for pattern. // // A substitute command should update both of them _vimData.LastSubstituteData <- Some { SearchPattern = pattern; Substitute = replace; Flags = flags} _vimData.LastSearchData <- SearchData(pattern, SearchPath.Forward, _globalSettings.WrapScan) /// Convert the provided whitespace into spaces. The conversion of /// tabs into spaces will be done based on the TabSize setting member x.GetAndNormalizeLeadingBlanksToSpaces line = let text = line |> SnapshotLineUtil.GetText |> Seq.takeWhile CharUtil.IsWhiteSpace |> List.ofSeq let builder = System.Text.StringBuilder() let tabSize = _localSettings.TabStop for c in text do match c with | ' ' -> builder.AppendChar ' ' | '\t' -> // Insert spaces up to the next tab size modulus. let count = let remainder = builder.Length % tabSize if remainder = 0 then tabSize else remainder for i = 1 to count do builder.AppendChar ' ' | _ -> builder.AppendChar ' ' builder.ToString(), text.Length /// Join the lines in the specified line range together. member x.Join (lineRange: SnapshotLineRange) joinKind = if lineRange.Count > 1 then use edit = _textBuffer.CreateEdit() // Get the collection of ITextSnapshotLine instances that we need to perform // the edit one. The last line doesn't need anything done to it. let lines = lineRange.Lines |> Seq.take (lineRange.Count - 1) match joinKind with | JoinKind.KeepEmptySpaces -> // Simplest implementation. Just delete relevant line breaks from the // ITextBuffer for line in lines do let span = Span(line.End.Position, line.LineBreakLength) edit.Delete span |> ignore | JoinKind.RemoveEmptySpaces -> for line in lines do // Getting the next line is safe here. By excluding the last line above we've // guaranteed there is at least one more line below us let nextLine = SnapshotUtil.GetLine lineRange.Snapshot (line.LineNumber + 1) let nextLineStartsWithCloseParen = SnapshotPointUtil.IsChar ')' nextLine.Start let replaceText = match SnapshotLineUtil.GetLastIncludedPoint line with | None -> if nextLineStartsWithCloseParen then "" else " " | Some point -> let c = SnapshotPointUtil.GetChar point if CharUtil.IsBlank c || nextLineStartsWithCloseParen then // When the line ends with a blank then we don't insert any new spaces // for the EOL "" elif (c = '.' || c = '!' || c = '?') && _globalSettings.JoinSpaces then " " else " " let span = Span(line.End.Position, line.LineBreakLength) edit.Replace(span, replaceText) |> ignore // Also need to delete any blanks at the start of the next line let blanksEnd = SnapshotLineUtil.GetFirstNonBlankOrEnd nextLine if blanksEnd <> nextLine.Start then let span = Span.FromBounds(nextLine.Start.Position, blanksEnd.Position) edit.Delete(span) |> ignore // Now position the caret on the new snapshot edit.Apply() |> ignore /// Load a file into a new window, optionally moving the caret to the first /// non-blank on a specific line or to a specific line and column member x.LoadFileIntoNewWindow file lineNumber columnNumber = match _vimHost.LoadFileIntoNewWindow file lineNumber columnNumber with | Some textView -> // Try to ensure that our view flags are enforced in the new window. match x.TryGetCommonOperationsForTextView textView with | Some commonOperations -> commonOperations.EnsureAtCaret ViewFlags.Standard | None -> () Result.Succeeded | None -> Resources.Common_CouldNotOpenFile file |> Result.Failed // Puts the provided StringData at the given point in the ITextBuffer. Does not attempt // to move the caret as a result of this operation member x.Put point stringData opKind = match stringData with | StringData.Simple str -> // Before inserting normalize the new lines in the string to the newline at the // put position in the buffer. This doesn't appear to be documented anywhere but // can be verified experimentally let str = let newLine = x.GetNewLineText point EditUtil.NormalizeNewLines str newLine // Simple strings can go directly in at the position. Need to adjust the text if // we are inserting at the end of the buffer let text = let newLine = EditUtil.NewLine _editorOptions _textBuffer match opKind with | OperationKind.LineWise -> if SnapshotPointUtil.IsEndPoint point && not (SnapshotPointUtil.IsStartOfLine point) then // At the end of the file without a trailing line break so we need to // manipulate the new line character a bit. // It's typically at the end of the line but at the end of the // ITextBuffer we need it to be at the beginning since there is no newline // to append after at the end of the buffer. let str = EditUtil.RemoveEndingNewLine str newLine + str elif not (SnapshotPointUtil.IsStartOfLine point) then // Edit in the middle of the line. Need to prefix the string with a newline // in order to correctly insert here. // // This type of put will occur when a linewise register value is inserted // from a visual mode character selection newLine + str elif not (EditUtil.EndsWithNewLine str) then // All other linewise operation should have a trailing newline to ensure a // new line is actually inserted str + newLine else str | OperationKind.CharacterWise -> // Simplest insert. No changes needed str _textBuffer.Insert(point.Position, text) |> ignore | StringData.Block col -> use edit = _textBuffer.CreateEdit() match opKind with | OperationKind.CharacterWise -> // Collection strings are inserted at the original character // position down the set of lines creating whitespace as needed // to match the indent let column = SnapshotColumn(point) let lineNumber, columnNumber = column.LineNumber, column.ColumnNumber // First break the strings into the collection to edit against // existing lines and those which need to create new lines at // the end of the buffer let originalSnapshot = point.Snapshot let insertCol, appendCol = let lastLineNumber = SnapshotUtil.GetLastLineNumber originalSnapshot let insertCount = min ((lastLineNumber - lineNumber) + 1) col.Count (Seq.take insertCount col, Seq.skip insertCount col) // Insert the text into each of the existing lines. insertCol |> Seq.iteri (fun offset str -> let line = lineNumber + offset |> SnapshotUtil.GetLine originalSnapshot let column = SnapshotColumn(line) let columnCount = SnapshotLineUtil.GetColumnsCount SearchPath.Forward line if columnCount < columnNumber then let prefix = String.replicate (columnNumber - columnCount) " " edit.Insert(line.End.Position, prefix + str) |> ignore else let offset = column.Add(columnNumber).Offset edit.Insert(line.Start.Position + offset, str) |> ignore) // Add the text to the end of the buffer. if not (Seq.isEmpty appendCol) then let prefix = (EditUtil.NewLine _editorOptions _textBuffer) + (String.replicate columnNumber " ") let text = Seq.fold (fun text str -> text + prefix + str) "" appendCol let endPoint = SnapshotUtil.GetEndPoint originalSnapshot edit.Insert(endPoint.Position, text) |> ignore | OperationKind.LineWise -> // Strings are inserted line wise into the ITextBuffer. Build up an // aggregate string and insert it here let text = col |> Seq.fold (fun state elem -> state + elem + (EditUtil.NewLine _editorOptions _textBuffer)) StringUtil.Empty edit.Insert(point.Position, text) |> ignore edit.Apply() |> ignore member x.Beep() = if not _localSettings.GlobalSettings.VisualBell then _vimHost.Beep() member x.DoWithOutlining func = match _outliningManager with | None -> x.Beep() | Some outliningManager -> func outliningManager member x.CheckDirty func = if _vimHost.IsDirty _textView.TextBuffer then _statusUtil.OnError Resources.Common_NoWriteSinceLastChange else func() member x.RaiseSearchResultMessage searchResult = CommonUtil.RaiseSearchResultMessage _statusUtil searchResult /// Record last change start and end positions /// (spans must be from different snapshots) member x.RecordLastChange (oldSpan: SnapshotSpan) (newSpan: SnapshotSpan) = Contract.Requires(oldSpan.Snapshot <> newSpan.Snapshot) x.RecordLastChangeOrYank oldSpan newSpan /// Record last yank start and end positions member x.RecordLastYank (span: SnapshotSpan) = // If ':set clipboard=unnamed' is in effect, copy the yanked span to // the clipboard using the editor to preserve formatting. Feature // requested in issue #1920. if Util.IsFlagSet _globalSettings.ClipboardOptions ClipboardOptions.Unnamed then - SelectionSpan.FromSpan(span.End, span, isReversed = false) - |> TextViewUtil.SelectSpan _textView - _editorOperations.CopySelection() |> ignore - TextViewUtil.ClearSelection _textView + let caretPoint = x.CaretPoint + try + SelectionSpan.FromSpan(span.End, span, isReversed = false) + |> TextViewUtil.SelectSpan _textView + _editorOperations.CopySelection() |> ignore + TextViewUtil.ClearSelection _textView + finally + TextViewUtil.MoveCaretToPoint _textView caretPoint x.RecordLastChangeOrYank span span /// Record last change or yankstart and end positions /// (it is a yank if the old span and the new span are the same) member x.RecordLastChangeOrYank oldSpan newSpan = let startPoint = SnapshotSpanUtil.GetStartPoint newSpan let endPoint = SnapshotSpanUtil.GetEndPoint newSpan let endPoint = match SnapshotSpanUtil.GetLastIncludedPoint newSpan with | Some point -> if SnapshotPointUtil.IsInsideLineBreak point then point else endPoint | None -> endPoint _vimTextBuffer.LastChangeOrYankStart <- Some startPoint _vimTextBuffer.LastChangeOrYankEnd <- Some endPoint let lineRange = if newSpan.Length = 0 then oldSpan else newSpan |> SnapshotLineRange.CreateForSpan let lineCount = lineRange.Count if lineCount >= 3 then if newSpan.Length = 0 then Resources.Common_LinesDeleted lineCount elif oldSpan = newSpan then Resources.Common_LinesYanked lineCount else Resources.Common_LinesChanged lineCount |> _statusUtil.OnStatus /// Undo 'count' operations in the ITextBuffer and ensure the caret is on the screen /// after the undo completes member x.Undo count = x.EnsureUndoHasView() _undoRedoOperations.Undo count x.AdjustCaretForVirtualEdit() x.EnsureAtPoint x.CaretPoint ViewFlags.Standard /// Redo 'count' operations in the ITextBuffer and ensure the caret is on the screen /// after the redo completes member x.Redo count = x.EnsureUndoHasView() _undoRedoOperations.Redo count x.AdjustCaretForVirtualEdit() x.EnsureAtPoint x.CaretPoint ViewFlags.Standard /// Restore spaces to caret, or move to start of line if 'startofline' is set member x.RestoreSpacesToCaret (spacesToCaret: int) (useStartOfLine: bool) = if useStartOfLine && _globalSettings.StartOfLine then let point = SnapshotLineUtil.GetFirstNonBlankOrEnd x.CaretLine TextViewUtil.MoveCaretToPoint _textView point else let virtualColumn = if _vimTextBuffer.UseVirtualSpace then VirtualSnapshotColumn.GetColumnForSpaces(x.CaretLine, spacesToCaret, _localSettings.TabStop) else let column = SnapshotColumn.GetColumnForSpacesOrEnd(x.CaretLine, spacesToCaret, _localSettings.TabStop) VirtualSnapshotColumn(column) x.MoveCaretToVirtualPoint virtualColumn.VirtualStartPoint ViewFlags.VirtualEdit x.MaintainCaretColumn <- MaintainCaretColumn.Spaces spacesToCaret /// Synchronously ensure that the given view properties are met at the given point member x.EnsureAtPointSync point viewFlags = let point = x.MapPointNegativeToCurrentSnapshot point if Util.IsFlagSet viewFlags ViewFlags.TextExpanded then x.EnsurePointExpanded point if Util.IsFlagSet viewFlags ViewFlags.Visible then x.EnsurePointVisible point if Util.IsFlagSet viewFlags ViewFlags.ScrollOffset then x.AdjustTextViewForScrollOffsetAtPoint point if Util.IsFlagSet viewFlags ViewFlags.VirtualEdit && point.Position = x.CaretPoint.Position then x.AdjustCaretForVirtualEdit() /// Ensure the view properties are met at the caret member x.EnsureAtCaret viewFlags = if _vimBufferData.CaretIndex = 0 then x.DoActionWhenReady (fun () -> x.EnsureAtPointSync x.CaretPoint viewFlags) /// Ensure that the given view properties are met at the given point member x.EnsureAtPoint point viewFlags = x.DoActionWhenReady (fun () -> x.EnsureAtPointSync point viewFlags) /// Ensure the given SnapshotPoint is not in a collapsed region on the screen member x.EnsurePointExpanded point = match _outliningManager with | None -> () | Some outliningManager -> let span = SnapshotSpan(point, 0) outliningManager.ExpandAll(span, fun _ -> true) |> ignore /// Ensure the point is on screen / visible member x.EnsurePointVisible (point: SnapshotPoint) = TextViewUtil.CheckScrollToPoint _textView point if point.Position = x.CaretPoint.Position then TextViewUtil.EnsureCaretOnScreen _textView else _vimHost.EnsureVisible _textView point member x.GetRegisterName name = match name with | Some name -> name | None -> if Util.IsFlagSet _globalSettings.ClipboardOptions ClipboardOptions.Unnamed then RegisterName.SelectionAndDrop SelectionAndDropRegister.Star else RegisterName.Unnamed member x.GetRegister name = let name = x.GetRegisterName name _registerMap.GetRegister name /// Updates the given register with the specified value. This will also update /// other registers based on the type of update that is being performed. See /// :help registers for the full details member x.SetRegisterValue (name: RegisterName option) operation (value: RegisterValue) = let name, isUnnamedOrMissing, isMissing = match name with | None -> x.GetRegisterName None, true, true | Some name -> name, name = RegisterName.Unnamed, false if name <> RegisterName.Blackhole then _registerMap.SetRegisterValue name value // If this is not the unnamed register then the unnamed register // needs to be updated to the value of the register we just set // (or appended to). if name <> RegisterName.Unnamed then _registerMap.GetRegister name |> (fun register -> register.RegisterValue) |> _registerMap.SetRegisterValue RegisterName.Unnamed let hasNewLine = match value.StringData with | StringData.Block col -> Seq.exists EditUtil.HasNewLine col | StringData.Simple str -> EditUtil.HasNewLine str // Performs a numbered delete. Shifts all of the values down and puts // the new value into register 1 // // The documentation for registers 1-9 says this doesn't occur when a named // register is used. Actual behavior shows this is not the case. let doNumberedDelete () = for i in [9;8;7;6;5;4;3;2] do let cur = RegisterNameUtil.NumberToRegister i |> Option.get let prev = RegisterNameUtil.NumberToRegister (i - 1) |> Option.get let prevRegister = _registerMap.GetRegister prev _registerMap.SetRegisterValue cur prevRegister.RegisterValue _registerMap.SetRegisterValue (RegisterName.Numbered NumberedRegister.Number1) value // Update the numbered register based on the type of the operation match operation with | RegisterOperation.Delete -> if hasNewLine then doNumberedDelete() // Use small delete register unless a register was explicitly named else if isMissing then _registerMap.SetRegisterValue RegisterName.SmallDelete value | RegisterOperation.BigDelete -> doNumberedDelete() if not hasNewLine && name = RegisterName.Unnamed then _registerMap.SetRegisterValue RegisterName.SmallDelete value | RegisterOperation.Yank -> // If the register name was missing or explicitly the unnamed register then it needs // to update register 0. if isUnnamedOrMissing then _registerMap.SetRegisterValue (RegisterName.Numbered NumberedRegister.Number0) value /// Toggle the use of typing language characters for insert or search /// (see vim ':help i_CTRL-^' and ':help c_CTRL-^') member x.ToggleLanguage isForInsert = let keyMap = _vimBufferData.VimTextBuffer.LocalKeyMap let languageMappings = keyMap.GetKeyMappings(KeyRemapMode.Language, includeGlobal = true) let languageMappingsAreDefined = not (Seq.isEmpty languageMappings) if isForInsert || _globalSettings.ImeSearch = -1 then if languageMappingsAreDefined then match _globalSettings.ImeInsert with | 1 -> _globalSettings.ImeInsert <- 0 | _ -> _globalSettings.ImeInsert <- 1 else match _globalSettings.ImeInsert with | 2 -> _globalSettings.ImeInsert <- 0 | _ -> _globalSettings.ImeInsert <- 2 else if languageMappingsAreDefined then match _globalSettings.ImeSearch with | 1 -> _globalSettings.ImeSearch <- 0 | _ -> _globalSettings.ImeSearch <- 1 else match _globalSettings.ImeSearch with | 2 -> _globalSettings.ImeSearch <- 0 | _ -> _globalSettings.ImeSearch <- 2 /// Map the specified point with negative tracking to the current snapshot member x.MapPointNegativeToCurrentSnapshot (point: SnapshotPoint) = x.MapPointToCurrentSnapshot point PointTrackingMode.Negative /// Map the specified point with positive tracking to the current snapshot member x.MapPointPositiveToCurrentSnapshot (point: SnapshotPoint) = x.MapPointToCurrentSnapshot point PointTrackingMode.Positive /// Map the specified point with the specified tracking to the current snapshot member x.MapPointToCurrentSnapshot (point: SnapshotPoint) (pointTrackingMode: PointTrackingMode) = let snapshot = _textBuffer.CurrentSnapshot TrackingPointUtil.GetPointInSnapshot point pointTrackingMode snapshot |> Option.defaultValue (SnapshotPoint(snapshot, min point.Position snapshot.Length)) /// Map the specified caret point to the current snapshot member x.MapCaretPointToCurrentSnapshot (point: VirtualSnapshotPoint) = if _vimTextBuffer.UseVirtualSpace then let snapshot = _textBuffer.CurrentSnapshot let pointTrackingMode = PointTrackingMode.Negative match TrackingPointUtil.GetVirtualPointInSnapshot point pointTrackingMode snapshot with | Some point -> point | None -> let defaultPoint = SnapshotPoint(snapshot, min point.Position.Position snapshot.Length) VirtualSnapshotPoint(defaultPoint, point.VirtualSpaces) else point.Position |> x.MapPointNegativeToCurrentSnapshot |> VirtualSnapshotPointUtil.OfPoint /// Map the specified selected span to the current snapshot member x.MapSelectedSpanToCurrentSnapshot (span: SelectionSpan) = let caretPoint = x.MapCaretPointToCurrentSnapshot span.CaretPoint let anchorPoint = x.MapCaretPointToCurrentSnapshot span.AnchorPoint let activcePoint = x.MapCaretPointToCurrentSnapshot span.ActivePoint SelectionSpan(caretPoint, anchorPoint, activcePoint) /// Add a new caret at the specified point member x.AddCaretAtPoint (point: VirtualSnapshotPoint) = let contains = VirtualSnapshotSpanUtil.ContainsOrEndsWith let isContainedByExistingSpan = x.SelectedSpans |> Seq.exists (fun span -> contains span.Span point) let remainingSpans = x.SelectedSpans |> Seq.filter (fun span -> not (contains span.Span point)) |> Seq.toArray if remainingSpans.Length > 0 || not isContainedByExistingSpan then seq { yield! remainingSpans if not isContainedByExistingSpan then yield SelectionSpan(point) } |> x.SetSelectedSpans /// Add the specified selected span member x.AddSelectedSpan selectedSpan = seq { yield! x.SelectedSpans yield selectedSpan } |> x.SetSelectedSpans /// Add a new caret at the mouse point member x.AddCaretAtMousePoint () = match x.MousePoint with | Some mousePoint -> x.AddCaretAtPoint mousePoint | None -> () /// Add a caret or selection on an adjacent line in the specified direction member x.AddCaretOrSelectionOnAdjacentLine direction = // Get the selected spans sorted by caret point. let selectedSpans = x.SelectedSpans |> Seq.sortBy (fun span -> span.CaretPoint.Position.Position) |> Seq.toList // Add a selection on the specified line number in the same column as // the primary caret. let addSelectionOnLineNumber lineNumber = let primarySelectedSpan = x.PrimarySelectedSpan let snapshot = primarySelectedSpan.CaretPoint.Position.Snapshot let line = SnapshotUtil.GetLine snapshot lineNumber let getRelativePoint point = let spaces = x.GetSpacesToVirtualPoint point let column = x.GetAppropriateColumnForSpaces line spaces column.VirtualStartPoint let caretPoint = getRelativePoint primarySelectedSpan.CaretPoint let anchorPoint = getRelativePoint primarySelectedSpan.AnchorPoint let activePoint = getRelativePoint primarySelectedSpan.ActivePoint SelectionSpan(caretPoint, anchorPoint, activePoint) |> x.AddSelectedSpan // Choose an appropriate line to add the caret on. match direction with | Direction.Up -> let firstLine = selectedSpans.[0].CaretPoint |> VirtualSnapshotPointUtil.GetContainingLine if firstLine.LineNumber > 0 then addSelectionOnLineNumber (firstLine.LineNumber - 1) | Direction.Down -> let lastLine = selectedSpans.[selectedSpans.Length - 1].CaretPoint |> VirtualSnapshotPointUtil.GetContainingLine let lastLineNumber = SnapshotUtil.GetLastNormalizedLineNumber lastLine.Snapshot if lastLine.LineNumber < lastLineNumber then addSelectionOnLineNumber (lastLine.LineNumber + 1) | _ -> () /// Run the specified action for all selections member x.RunForAllSelections action = // Unless there are multiple selections just do the action once and // return its result normally. if x.IsMultiSelectionSupported then let selectedSpans = x.SelectedSpans |> Seq.toList if selectedSpans.Length > 1 then x.RunForAllSelectionsCore action selectedSpans else action() else action() /// Run the specified action for the specified selected spans member x.RunForAllSelectionsCore action selectedSpans = // Get the current kind of visual mode, if any. let visualModeKind = _vimTextBuffer.ModeKind |> VisualKind.OfModeKind // Get any mode argument from the specified command result. let getModeArgument result = match result with | CommandResult.Completed modeSwitch -> match modeSwitch with | ModeSwitch.SwitchModeWithArgument (_, modeArgument) -> Some modeArgument | _ -> None | _ -> None // Get any linked transaction from the specified command result. let getLinkedTransaction result = match getModeArgument result with | Some modeArgument -> modeArgument.LinkedUndoTransaction | _ -> None // Get any visual selection from the specified command result. let getVisualSelection result = match getModeArgument result with | Some (ModeArgument.InitialVisualSelection (visualSelection, _)) -> _globalSettings.SelectionKind |> visualSelection.GetPrimarySelectedSpan |> Some | _ -> None // Get any switch to mode kind let getSwitchToModeKind result = match result with | CommandResult.Completed modeSwitch -> match modeSwitch with | ModeSwitch.SwitchMode modeKind -> Some modeKind | ModeSwitch.SwitchModeWithArgument (modeKind, _) -> Some modeKind | _ -> None | _ -> None // Get any switch to visual mode from the specifed command result. let getSwitchToVisualKind result = match getSwitchToModeKind result with | Some modeKind -> match modeKind with | ModeKind.VisualCharacter -> Some VisualKind.Character | ModeKind.VisualLine -> Some VisualKind.Line | ModeKind.VisualBlock -> Some VisualKind.Block | _ -> None | _ -> None // Create a linked undo transaction. let createTransaction () = let name = "MultiSelection" let flags = LinkedUndoTransactionFlags.CanBeEmpty _undoRedoOperations.CreateLinkedUndoTransactionWithFlags name flags // Run the action and complete any embedded linked transaction. let runActionAndCompleteTransaction action = let result = action() match getLinkedTransaction result with | Some linkedTransaction -> linkedTransaction.Complete() | None -> () result // Get the effective selected span. let getVisualSelectedSpan visualKind (oldSelectedSpan: SelectionSpan) = let oldSelectedSpan = x.MapSelectedSpanToCurrentSnapshot oldSelectedSpan let snapshot = _textView.TextSnapshot let oldAnchorPoint = oldSelectedSpan.AnchorPoint let anchorPoint = match _vimBufferData.VisualAnchorPoint with | Some trackingPoint -> match TrackingPointUtil.GetPoint snapshot trackingPoint with | Some point -> VirtualSnapshotPointUtil.OfPoint point | None -> oldAnchorPoint | None -> oldAnchorPoint let anchorPointChanged = oldAnchorPoint <> anchorPoint let caretPoint = x.CaretVirtualPoint let useVirtualSpace = _vimBufferData.VimTextBuffer.UseVirtualSpace let selectionKind = _globalSettings.SelectionKind let tabStop = _localSettings.TabStop let visualSelection = VisualSelection.CreateForVirtualPoints visualKind anchorPoint caretPoint tabStop useVirtualSpace let adjustSelection = match selectionKind with | SelectionKind.Exclusive -> true | SelectionKind.Inclusive -> oldSelectedSpan.IsReversed && oldSelectedSpan.Length <> 1 && not anchorPointChanged let visualSelection = if adjustSelection then visualSelection.AdjustForSelectionKind SelectionKind.Exclusive else visualSelection let span = visualSelection.GetPrimarySelectedSpan selectionKind if selectionKind = SelectionKind.Inclusive && span.Length = 1 && span.CaretPoint = span.Start then SelectionSpan(span.CaretPoint, span.Start, span.End) else span // Get the initial selected span for specified kind of visual mode. let getInitialSelection visualKind = let caretPoint = TextViewUtil.GetCaretVirtualPoint _textView let tabStop = _localSettings.TabStop let selectionKind = _globalSettings.SelectionKind let useVirtualSpace = _vimBufferData.VimTextBuffer.UseVirtualSpace let visualSelection = VisualSelection.CreateInitial visualKind caretPoint tabStop selectionKind useVirtualSpace visualSelection.GetPrimarySelectedSpan selectionKind // Collect the command result and new selected span or any embedded // visual span, if present. let getResultingSpan oldSelectedSpan result = match getSwitchToModeKind result with | Some modeKind when VisualKind.OfModeKind modeKind |> Option.isNone -> SelectionSpan(x.CaretVirtualPoint) | _ -> match getSwitchToVisualKind result with | Some visualKind -> getInitialSelection visualKind | None -> match visualModeKind with | Some modeKind -> getVisualSelectedSpan modeKind oldSelectedSpan | None -> match getVisualSelection result with | Some selectedSpan -> selectedSpan | None -> x.PrimarySelectedSpan // Set a temporary visual anchor point. let setVisualAnchorPoint (anchorPoint: VirtualSnapshotPoint) = if Option.isSome visualModeKind then let snapshot = anchorPoint.Position.Snapshot let position = anchorPoint.Position.Position let trackingPoint = snapshot.CreateTrackingPoint(position, PointTrackingMode.Negative) |> Some _vimBufferData.VisualAnchorPoint <- trackingPoint // Get the results for all actions. let getResults () = seq { let indexedSpans = selectedSpans |> Seq.mapi (fun index span -> index, span) // Iterate over all selections. for index, oldSelectedSpan in indexedSpans do // Set the buffer local caret index. _vimBufferData.CaretIndex <- index diff --git a/Test/VimCoreTest/NormalModeIntegrationTest.cs b/Test/VimCoreTest/NormalModeIntegrationTest.cs index 24f2b8e..0ac3f88 100644 --- a/Test/VimCoreTest/NormalModeIntegrationTest.cs +++ b/Test/VimCoreTest/NormalModeIntegrationTest.cs @@ -9082,736 +9082,747 @@ namespace Vim.UnitTest _vimBuffer.Process(":nnoremap gj J"); _vimBuffer.Process(VimKey.Enter); _vimBuffer.Process(":map J 4j"); _vimBuffer.Process(VimKey.Enter); _vimBuffer.Process("J"); Assert.Equal(4, _textView.GetCaretLine().LineNumber); _textView.MoveCaretTo(0); _vimBuffer.Process("gj"); Assert.Equal("cat dog", _textView.GetLine(0).GetText()); } /// <summary> /// Delete with an append register should concatenate the values /// </summary> [WpfFact] public void Delete_Append() { Create("dog", "cat", "fish"); _vimBuffer.Process("\"cyaw"); _vimBuffer.Process("j"); _vimBuffer.Process("\"Cdw"); Assert.Equal("dogcat", _vimBuffer.RegisterMap.GetRegister('c').StringValue); Assert.Equal("dogcat", _vimBuffer.RegisterMap.GetRegister('C').StringValue); _vimBuffer.Process("\"cp"); Assert.Equal("dogcat", _textView.GetLine(1).GetText()); } /// <summary> /// Make sure that 'd0' is interpreted correctly as 'd{motion}' and not 'd#d'. 0 is not /// a count /// </summary> [WpfFact] public void Delete_BeginingOfLine() { Create("dog"); _textView.MoveCaretTo(1); _vimBuffer.Process("d0"); Assert.Equal("og", _textView.GetLine(0).GetText()); } /// <summary> /// Deleting a word left at the start of the line results in empty data and /// should not cause the register contents to be altered /// </summary> [WpfFact] public void Delete_LeftAtStartOfLine() { Create("dog", "cat"); UnnamedRegister.UpdateValue("hello"); _vimBuffer.Process("dh"); Assert.Equal("hello", UnnamedRegister.StringValue); Assert.Equal(0, _vimHost.BeepCount); } /// <summary> /// Delete when combined with the line down motion 'j' should delete two lines /// since it's deleting the result of the motion from the caret /// /// Convered by issue 288 /// </summary> [WpfFact] public void Delete_LineDown() { Create("abc", "def", "ghi", "jkl"); _textView.MoveCaretTo(1); _vimBuffer.Process("dj"); Assert.Equal("ghi", _textView.GetLine(0).GetText()); Assert.Equal("jkl", _textView.GetLine(1).GetText()); Assert.Equal(0, _textView.GetCaretPoint()); } /// <summary> /// When a delete of a search motion which wraps occurs a warning message should /// be displayed /// </summary> [WpfFact] public void Delete_SearchWraps() { Create("dog", "cat", "tree"); var didHit = false; _textView.MoveCaretToLine(1); _assertOnWarningMessage = false; _vimBuffer.WarningMessage += (_, args) => { Assert.Equal(Resources.Common_SearchForwardWrapped, args.Message); didHit = true; }; _vimBuffer.Process("d/dog", enter: true); Assert.Equal("cat", _textView.GetLine(0).GetText()); Assert.Equal("tree", _textView.GetLine(1).GetText()); Assert.True(didHit); } /// <summary> /// Delete a word at the end of the line. It should not delete the line break /// </summary> [WpfFact] public void Delete_WordEndOfLine() { Create("the cat", "chased the bird"); _textView.MoveCaretTo(4); _vimBuffer.Process("dw"); Assert.Equal("the ", _textView.GetLine(0).GetText()); Assert.Equal("chased the bird", _textView.GetLine(1).GetText()); } /// <summary> /// Delete a word at the end of the line where the next line doesn't start in column /// 0. This should still not cause the end of the line to delete /// </summary> [WpfFact] public void Delete_WordEndOfLineNextStartNotInColumnZero() { Create("the cat", " chased the bird"); _textView.MoveCaretTo(4); _vimBuffer.Process("dw"); Assert.Equal("the ", _textView.GetLine(0).GetText()); Assert.Equal(" chased the bird", _textView.GetLine(1).GetText()); } /// <summary> /// Delete across a line where the search ends in white space but not inside of /// column 0 /// </summary> [WpfFact] public void Delete_SearchAcrossLineNotInColumnZero() { Create("the cat", " chased the bird"); _textView.MoveCaretTo(4); _vimBuffer.Process("d/cha", enter: true); Assert.Equal("the chased the bird", _textView.GetLine(0).GetText()); } /// <summary> /// Delete across a line where the search ends in column 0 of the next line /// </summary> [WpfFact] public void Delete_SearchAcrossLineIntoColumnZero() { Create("the cat", "chased the bird"); _textView.MoveCaretTo(4); _vimBuffer.Process("d/cha", enter: true); Assert.Equal("the ", _textView.GetLine(0).GetText()); Assert.Equal("chased the bird", _textView.GetLine(1).GetText()); } /// <summary> /// Don't delete the new line when doing a 'daw' at the end of the line /// </summary> [WpfFact] public void Delete_AllWordEndOfLineIntoColumnZero() { Create("the cat", "chased the bird"); _textView.MoveCaretTo(4); _vimBuffer.Process("daw"); Assert.Equal("the", _textView.GetLine(0).GetText()); Assert.Equal("chased the bird", _textView.GetLine(1).GetText()); } /// <summary> /// Delete a word at the end of the line where the next line doesn't start in column /// 0. This should still not cause the end of the line to delete /// </summary> [WpfFact] public void Delete_AllWordEndOfLineNextStartNotInColumnZero() { Create("the cat", " chased the bird"); _textView.MoveCaretTo(4); _vimBuffer.Process("daw"); Assert.Equal("the", _textView.GetLine(0).GetText()); Assert.Equal(" chased the bird", _textView.GetLine(1).GetText()); } /// <summary> /// When virtual edit is enabled then deletion should not cause the caret to /// move if it would otherwise be in virtual space /// </summary> [WpfFact] public void Delete_WithVirtualEdit() { Create("cat", "dog"); _globalSettings.VirtualEdit = "onemore"; _textView.MoveCaretTo(2); _vimBuffer.Process("dl"); Assert.Equal("ca", _textView.GetLine(0).GetText()); Assert.Equal(2, _textView.GetCaretPoint().Position); } /// <summary> /// When virtual edit is not enabled then deletion should cause the caret to /// move if it would end up in virtual space /// </summary> [WpfFact] public void Delete_NoVirtualEdit() { Create("cat", "dog"); _globalSettings.VirtualEdit = string.Empty; _textView.MoveCaretTo(2); _vimBuffer.Process("dl"); Assert.Equal("ca", _textView.GetLine(0).GetText()); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// Make sure deleting the last line changes the line count in the buffer /// </summary> [WpfFact] public void DeleteLines_OnLastLine() { Create("foo", "bar"); _textView.MoveCaretTo(_textView.GetLine(1).Start); _vimBuffer.Process("dd"); Assert.Equal("foo", _textView.TextSnapshot.GetText()); Assert.Equal(1, _textView.TextSnapshot.LineCount); } [WpfFact] public void DeleteLines_OnLastNonEmptyLine() { Create("foo", "bar", ""); _textView.MoveCaretTo(_textView.GetLine(1).Start); _vimBuffer.Process("dd"); Assert.Equal(new[] { "foo", "" }, _textBuffer.GetLines()); } /// <summary> /// Delete lines with the special d#d count syntax /// </summary> [WpfFact] public void DeleteLines_Special_Simple() { Create("cat", "dog", "bear", "fish"); _vimBuffer.Process("d2d"); Assert.Equal("bear", _textBuffer.GetLine(0).GetText()); Assert.Equal(2, _textBuffer.CurrentSnapshot.LineCount); } /// <summary> /// Delete lines with both counts and make sure the counts are multiplied together /// </summary> [WpfFact] public void DeleteLines_Special_TwoCounts() { Create("cat", "dog", "bear", "fish", "tree"); _vimBuffer.Process("2d2d"); Assert.Equal("tree", _textBuffer.GetLine(0).GetText()); Assert.Equal(1, _textBuffer.CurrentSnapshot.LineCount); } /// <summary> /// The caret should be returned to the original first line when undoing a 'dd' /// command /// </summary> [WpfFact] public void DeleteLines_Undo() { Create("cat", "dog", "fish"); _textView.MoveCaretToLine(1); _vimBuffer.Process("ddu"); Assert.Equal(new[] { "cat", "dog", "fish" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetLine(1).Start, _textView.GetCaretPoint()); } /// <summary> /// Deleting to the end of the file should move the caret up /// </summary> [WpfFact] public void DeleteLines_ToEndOfFile() { // Reported in issue #2477. Create("cat", "dog", "fish", ""); _textView.MoveCaretToLine(1, 0); _vimBuffer.Process("dG"); Assert.Equal(new[] { "cat", "" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetPointInLine(0, 0), _textView.GetCaretPoint()); } /// <summary> /// Deleting lines should obey the 'startofline' setting /// </summary> [WpfFact] public void DeleteLines_StartOfLine() { // Reported in issue #2477. Create(" cat", " dog", " fish", ""); _textView.MoveCaretToLine(1, 2); _vimBuffer.Process("dd"); Assert.Equal(new[] { " cat", " fish", "" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetPointInLine(1, 1), _textView.GetCaretPoint()); } /// <summary> /// Deleting lines should preserve spaces to caret when /// 'nostartofline' is in effect /// </summary> [WpfFact] public void DeleteLines_NoStartOfLine() { // Reported in issue #2477. Create(" cat", " dog", " fish", ""); _globalSettings.StartOfLine = false; _textView.MoveCaretToLine(1, 2); _vimBuffer.Process("dd"); Assert.Equal(new[] { " cat", " fish", "" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetPointInLine(1, 2), _textView.GetCaretPoint()); } /// <summary> /// Subtract a negative decimal number /// </summary> [WpfFact] public void SubtractFromWord_Decimal_Negative() { Create(" -10"); _vimBuffer.Process(KeyInputUtil.CharWithControlToKeyInput('x')); Assert.Equal(" -11", _textBuffer.GetLine(0).GetText()); Assert.Equal(3, _textView.GetCaretPoint().Position); } /// <summary> /// Make sure we handle the 'gv' command to switch to the previous visual mode /// </summary> [WpfFact] public void SwitchPreviousVisualMode_Line() { Create("cats", "dogs", "fish"); var visualSelection = VisualSelection.NewLine( _textView.GetLineRange(0, 1), SearchPath.Forward, 1); _vimTextBuffer.LastVisualSelection = FSharpOption.Create(visualSelection); _vimBuffer.Process("gv"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); Assert.Equal(visualSelection, VisualSelection.CreateForSelection(_textView, VisualKind.Line, SelectionKind.Inclusive, tabStop: 4)); } /// <summary> /// Make sure we handle the 'gv' command to switch to the previous visual mode /// </summary> [WpfTheory] [InlineData("inclusive")] [InlineData("exclusive")] public void SwitchPreviousVisualMode_Character(string selection) { // Reported for 'exclusive' in issue #2186. Create("cat dog fish", ""); _globalSettings.Selection = selection; _vimBuffer.ProcessNotation("wve"); var span = _textBuffer.GetSpan(4, 3); Assert.Equal(span, _textView.GetSelectionSpan()); _vimBuffer.ProcessNotation("<Esc>"); _vimBuffer.ProcessNotation("gv"); Assert.Equal(span, _textView.GetSelectionSpan()); _vimBuffer.ProcessNotation("<Esc>"); _vimBuffer.ProcessNotation("gv"); Assert.Equal(span, _textView.GetSelectionSpan()); } /// <summary> /// Make sure the caret is positioned properly during undo /// </summary> [WpfFact] public void Undo_DeleteAllWord() { Create("cat", "dog"); _textView.MoveCaretTo(1); _vimBuffer.Process("daw"); _vimBuffer.Process("u"); Assert.Equal(0, _textView.GetCaretPoint().Position); } /// <summary> /// Undoing a change lines for a single line should put the caret at the start of the /// line which was changed /// </summary> [WpfFact] public void Undo_ChangeLines_OneLine() { Create(" cat"); _textView.MoveCaretTo(4); _vimBuffer.LocalSettings.AutoIndent = true; _vimBuffer.Process("cc"); _vimBuffer.Process(VimKey.Escape); _vimBuffer.Process("u"); Assert.Equal(" cat", _textBuffer.GetLine(0).GetText()); Assert.Equal(2, _textView.GetCaretPoint()); } /// <summary> /// Undoing a change lines for a multiple lines should put the caret at the start of the /// second line which was changed. /// </summary> [WpfFact] public void Undo_ChangeLines_MultipleLines() { Create("dog", " cat", " bear", " tree"); _textView.MoveCaretToLine(1); _vimBuffer.LocalSettings.AutoIndent = true; _vimBuffer.Process("3cc"); _vimBuffer.Process(VimKey.Escape); _vimBuffer.Process("u"); Assert.Equal("dog", _textBuffer.GetLine(0).GetText()); Assert.Equal(_textView.GetPointInLine(2, 2), _textView.GetCaretPoint()); } /// <summary> /// Need to ensure that ^ run from the first line doesn't register as an /// error. This ruins the ability to do macro playback /// </summary> [WpfFact] public void Issue909() { Create(" cat"); _textView.MoveCaretTo(2); _vimBuffer.Process("^"); Assert.Equal(0, _vimHost.BeepCount); } [WpfFact] public void Issue960() { Create(@"""aaa"", ""bbb"", ""ccc"""); _textView.MoveCaretTo(7); Assert.Equal('\"', _textView.GetCaretPoint().GetChar()); _vimBuffer.Process(@"di"""); Assert.Equal(@"""aaa"", """", ""ccc""", _textBuffer.GetLine(0).GetText()); Assert.Equal(8, _textView.GetCaretPoint().Position); } /// <summary> /// The word forward motion has special rules on how to handle motions that end on the /// first character of the next line and have blank lines above. Make sure we handle /// the case where the blank line is the originating line /// </summary> [WpfFact] public void DeleteWordOnBlankLineFromEnd() { Create("cat", " ", "dog"); _textView.MoveCaretToLine(1, 2); _vimBuffer.Process("dw"); Assert.Equal(new[] { "cat", " ", "dog" }, _textBuffer.GetLines()); Assert.Equal(_textBuffer.GetPointInLine(1, 1), _textView.GetCaretPoint()); } /// <summary> /// Similar to above but delete from the middle and make sure we take 2 characters with /// the delet instead of 1 /// </summary> [WpfFact] public void DeleteWordOnBlankLineFromMiddle() { Create("cat", " ", "dog"); _textView.MoveCaretToLine(1, 1); _vimBuffer.Process("dw"); Assert.Equal(new[] { "cat", " ", "dog" }, _textBuffer.GetLines()); Assert.Equal(_textBuffer.GetPointInLine(1, 0), _textView.GetCaretPoint()); } [WpfFact] public void DeleteWordOnDoubleBlankLineFromEnd() { Create("cat", " ", " ", "dog"); _textView.MoveCaretToLine(1, 2); _vimBuffer.Process("dw"); Assert.Equal(new[] { "cat", " ", " ", "dog" }, _textBuffer.GetLines()); Assert.Equal(_textBuffer.GetPointInLine(1, 1), _textView.GetCaretPoint()); } [WpfFact] public void InnerBlockYankAndPasteIsLinewise() { Create("if (true)", "{", " statement;", "}", "// after"); _textView.MoveCaretToLine(2); _vimBuffer.ProcessNotation("yi}"); Assert.True(UnnamedRegister.OperationKind.IsLineWise); _vimBuffer.ProcessNotation("p"); Assert.Equal( new[] { " statement;", " statement;" }, _textBuffer.GetLineRange(startLine: 2, endLine: 3).Lines.Select(x => x.GetText())); } [WpfFact] public void Issue1614() { Create("if (true)", "{", " statement;", "}", "// after"); _localSettings.ShiftWidth = 2; _textView.MoveCaretToLine(2); _vimBuffer.ProcessNotation(">i{"); Assert.Equal(" statement;", _textBuffer.GetLine(2).GetText()); } [WpfFact] public void Issue1738() { Create("dog", "tree"); _globalSettings.ClipboardOptions = ClipboardOptions.Unnamed; _vimBuffer.Process("yy"); Assert.Equal("dog" + Environment.NewLine, RegisterMap.GetRegister(0).StringValue); Assert.Equal("dog" + Environment.NewLine, RegisterMap.GetRegister(RegisterName.NewSelectionAndDrop(SelectionAndDropRegister.Star)).StringValue); } [WpfFact] public void Issue1827() { Create("penny", "dog"); RegisterMap.SetRegisterValue(0, "cat"); _vimBuffer.Process("dd"); Assert.Equal("cat", RegisterMap.GetRegister(0).StringValue); Assert.Equal("penny" + Environment.NewLine, RegisterMap.GetRegister(1).StringValue); } + [WpfFact] + public void LinewiseYank_ClipboardUnnamed() + { + // Reported in issue #2707 (migrated to issue #2735). + Create("dog", "tree"); + _globalSettings.ClipboardOptions = ClipboardOptions.Unnamed; + Assert.Equal(_textView.GetPointInLine(0, 0), _textView.GetCaretPoint()); + _vimBuffer.Process("yy"); + Assert.Equal(_textView.GetPointInLine(0, 0), _textView.GetCaretPoint()); + } + [WpfFact] public void OpenLink() { Create("foo https://github.com/VsVim/VsVim bar", ""); _textView.MoveCaretToLine(0, 8); var link = ""; _vimHost.OpenLinkFunc = arg => { link = arg; return true; }; _vimBuffer.Process("gx"); Assert.Equal("https://github.com/VsVim/VsVim", link); } [WpfFact] public void GoToLink() { Create("foo https://github.com/VsVim/VsVim bar", ""); _textView.MoveCaretToLine(0, 8); var link = ""; _vimHost.OpenLinkFunc = arg => { link = arg; return true; }; _vimBuffer.ProcessNotation("<C-]>"); Assert.Equal("https://github.com/VsVim/VsVim", link); } [WpfFact] public void GoToUppercaseLink() { Create("foo HTTPS://GITHUB.COM/VSVIM/VSVIM bar", ""); _textView.MoveCaretToLine(0, 8); var link = ""; _vimHost.OpenLinkFunc = arg => { link = arg; return true; }; _vimBuffer.ProcessNotation("<C-]>"); Assert.Equal("HTTPS://GITHUB.COM/VSVIM/VSVIM", link); } [WpfFact] public void GoToLinkWithMouse() { Create("foo https://github.com/VsVim/VsVim bar", ""); var point = _textView.GetPointInLine(0, 8); var link = ""; _vimHost.OpenLinkFunc = arg => { link = arg; return true; }; _testableMouseDevice.Point = point; _vimBuffer.ProcessNotation("<C-LeftMouse>"); Assert.Equal("https://github.com/VsVim/VsVim", link); Assert.Equal(point, _textView.GetCaretPoint()); Assert.Equal(0, _vimHost.GoToDefinitionCount); } [WpfFact] public void MouseDoesNotAffectLastCommand() { Create("foo https://github.com/VsVim/VsVim bar", ""); _textView.SetVisibleLineCount(2); _vimBuffer.ProcessNotation("yyp"); var point = _textView.GetPointInLine(0, 8); var link = ""; _vimHost.OpenLinkFunc = arg => { link = arg; return true; }; _testableMouseDevice.Point = point; _vimBuffer.ProcessNotation("<C-LeftMouse>"); Assert.Equal("https://github.com/VsVim/VsVim", link); Assert.Equal(point, _textView.GetCaretPoint()); Assert.Equal(0, _vimHost.GoToDefinitionCount); Assert.True(WithLastNormalCommand(x => x.IsPutAfterCaret)); _vimBuffer.ProcessNotation("<C-LeftRelease>"); Assert.True(WithLastNormalCommand(x => x.IsPutAfterCaret)); } } public sealed class MotionWrapTest : NormalModeIntegrationTest { /// <summary> /// Right arrow wrapping /// </summary> [WpfFact] public void RightArrow() { Create("cat", "bat"); _globalSettings.WhichWrap = "<,>"; _vimBuffer.ProcessNotation("<Right><Right><Right>"); Assert.Equal(_textView.GetLine(1).Start, _textView.GetCaretPoint()); _vimBuffer.ProcessNotation("<Right><Right><Right>"); Assert.Equal(_textView.GetLine(1).Start.Add(2), _textView.GetCaretPoint()); } /// <summary> /// Right arrow wrapping with final newline /// </summary> [WpfFact] public void RightArrowWithFinalNewLine() { Create("cat", "bat", ""); _globalSettings.WhichWrap = "<,>"; _vimBuffer.ProcessNotation("<Right><Right><Right>"); Assert.Equal(_textView.GetLine(1).Start, _textView.GetCaretPoint()); _vimBuffer.ProcessNotation("<Right><Right><Right>"); Assert.Equal(_textView.GetLine(1).Start.Add(2), _textView.GetCaretPoint()); } } public sealed class RepeatLineCommand : NormalModeIntegrationTest { /// <summary> /// Simple repeat of the last line command /// </summary> [WpfFact] public void Basic() { Create("cat", "bat", "dog", ""); _textView.MoveCaretToLine(1); _vimBuffer.ProcessNotation(":s/^/xxx /<Enter>"); Assert.Equal(new[] { "cat", "xxx bat", "dog", "" }, _textBuffer.GetLines()); _textView.MoveCaretToLine(0); _vimBuffer.ProcessNotation("@:"); Assert.Equal(new[] { "xxx cat", "xxx bat", "dog", "" }, _textBuffer.GetLines()); _textView.MoveCaretToLine(2); _vimBuffer.ProcessNotation("@:"); Assert.Equal(new[] { "xxx cat", "xxx bat", "xxx dog", "" }, _textBuffer.GetLines()); } /// <summary> /// Repeat of the last line command with a count /// </summary> [WpfFact] public void WithCount() { Create("cat", "bat", "dog", "bear", "rat", ""); _textView.MoveCaretToLine(2); _vimBuffer.ProcessNotation(":delete<Enter>"); Assert.Equal(new[] { "cat", "bat", "bear", "rat", "" }, _textBuffer.GetLines()); _textView.MoveCaretToLine(1); _vimBuffer.ProcessNotation("2@:"); Assert.Equal(new[] { "cat", "rat", "" }, _textBuffer.GetLines()); } } public class VirtualEditTest : NormalModeIntegrationTest { protected override void Create(params string[] lines) { base.Create(lines); _globalSettings.VirtualEdit = "all"; _globalSettings.WhichWrap = "<,>"; _localSettings.TabStop = 4; } public sealed class VirtualEditNormal : VirtualEditTest { /// <summary> /// We should be able to move caret cursor in a tiny box after a variety of lines /// and return to the same buffer position /// </summary> /// <param name="line1"></param> /// <param name="line2"></param> [WpfTheory] [InlineData("", "")] [InlineData("cat", "dog")] [InlineData("cat", "")] [InlineData("", "dog")] [InlineData("cat", "\tdog")] [InlineData("\tcat", "dog")] [InlineData("cat dog bat bear", "cat dog bat bear")] [InlineData("", "cat dog bat bear")] [InlineData("cat dog bat bear", "")] public void CaretBox(string line1, string line2) { Create(line1, line2, ""); _vimBuffer.ProcessNotation("10l"); Assert.Equal(_textBuffer.GetVirtualPointInLine(0, 10), _textView.GetCaretVirtualPoint()); _vimBuffer.ProcessNotation("jlkh"); Assert.Equal(_textBuffer.GetVirtualPointInLine(0, 10), _textView.GetCaretVirtualPoint()); _vimBuffer.ProcessNotation("<Down><Right><Up><Left>"); Assert.Equal(_textBuffer.GetVirtualPointInLine(0, 10), _textView.GetCaretVirtualPoint()); } } public sealed class VirtualEditInsert : VirtualEditTest { /// <summary> /// We should be able to move caret cursor in a tiny box after a variety of lines /// and return to the same buffer position /// </summary> /// <param name="line1"></param> /// <param name="line2"></param> [WpfTheory] [InlineData("", "")] [InlineData("cat", "dog")] [InlineData("cat", "")] [InlineData("", "dog")] [InlineData("cat", "\tdog")] [InlineData("\tcat", "dog")] [InlineData("cat dog bat bear", "cat dog bat bear")] [InlineData("", "cat dog bat bear")] [InlineData("cat dog bat bear", "")] public void CaretBox(string line1, string line2) { Create(line1, line2, ""); _vimBuffer.ProcessNotation("10li"); Assert.Equal(_textBuffer.GetVirtualPointInLine(0, 10), _textView.GetCaretVirtualPoint()); _vimBuffer.ProcessNotation("<Down><Right><Up><Left>"); Assert.Equal(_textBuffer.GetVirtualPointInLine(0, 10), _textView.GetCaretVirtualPoint()); } } } } }
VsVim/VsVim
a3139c671a31aeef6bc6e976f89da0e66f411782
Fix caret top on lines below CodeLens annotations
diff --git a/Src/VimWpf/Implementation/BlockCaret/BlockCaret.cs b/Src/VimWpf/Implementation/BlockCaret/BlockCaret.cs index 34439ad..479b050 100644 --- a/Src/VimWpf/Implementation/BlockCaret/BlockCaret.cs +++ b/Src/VimWpf/Implementation/BlockCaret/BlockCaret.cs @@ -1,846 +1,846 @@ using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Threading; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Formatting; namespace Vim.UI.Wpf.Implementation.BlockCaret { internal sealed class BlockCaret : IBlockCaret { private readonly struct CaretData { internal readonly int CaretIndex; internal readonly CaretDisplay CaretDisplay; internal readonly double CaretOpacity; internal readonly UIElement Element; internal readonly Color? Color; internal readonly Size Size; internal readonly double YDisplayOffset; internal readonly double BaselineOffset; internal readonly string CaretCharacter; internal CaretData( int caretIndex, CaretDisplay caretDisplay, double caretOpacity, UIElement element, Color? color, Size size, double displayOffset, double baselineOffset, string caretCharacter) { CaretIndex = caretIndex; CaretDisplay = caretDisplay; CaretOpacity = caretOpacity; Element = element; Color = color; Size = size; YDisplayOffset = displayOffset; BaselineOffset = baselineOffset; CaretCharacter = caretCharacter; } } private static readonly Point s_invalidPoint = new Point(double.NaN, double.NaN); private readonly IVimBufferData _vimBufferData; private readonly IWpfTextView _textView; private readonly ISelectionUtil _selectionUtil; private readonly IProtectedOperations _protectedOperations; private readonly IEditorFormatMap _editorFormatMap; private readonly IClassificationFormatMap _classificationFormatMap; private readonly IAdornmentLayer _adornmentLayer; private readonly List<object> _tags = new List<object>(); private readonly HashSet<object> _adornmentsPresent = new HashSet<object>(); private readonly DispatcherTimer _blinkTimer; private readonly IControlCharUtil _controlCharUtil; private List<VirtualSnapshotPoint> _caretPoints = new List<VirtualSnapshotPoint>(); private Dictionary<int, CaretData> _caretDataMap = new Dictionary<int, CaretData>(); private CaretDisplay _caretDisplay; private FormattedText _formattedText; private bool _isDestroyed; private bool _isUpdating; private double _caretOpacity = 1.0; public ITextView TextView { get { return _textView; } } public CaretDisplay CaretDisplay { get { return _caretDisplay; } set { if (_caretDisplay != value) { _caretDisplay = value; UpdateCaret(); } } } public double CaretOpacity { get { return _caretOpacity; } set { if (_caretOpacity != value) { _caretOpacity = value; UpdateCaret(); } } } private IWpfTextViewLine GetTextViewLineContainingPoint(VirtualSnapshotPoint caretPoint) { try { if (!_textView.IsClosed && !_textView.InLayout) { var textViewLines = _textView.TextViewLines; if (textViewLines != null && textViewLines.IsValid) { var textViewLine = textViewLines.GetTextViewLineContainingBufferPosition(caretPoint.Position); if (textViewLine != null && textViewLine.IsValid) { return textViewLine; } } } } catch (InvalidOperationException ex) { VimTrace.TraceError(ex); } return null; } /// <summary> /// Is the real caret visible in some way? /// </summary> private bool IsRealCaretVisible(VirtualSnapshotPoint caretPoint, out ITextViewLine textViewLine) { textViewLine = null; if (_textView.HasAggregateFocus) { textViewLine = GetTextViewLineContainingPoint(caretPoint); if (textViewLine != null && textViewLine.VisibilityState != VisibilityState.Unattached) { return true; } textViewLine = null; } return false; } private bool IsRealCaretVisible(VirtualSnapshotPoint caretPoint) { return IsRealCaretVisible(caretPoint, out _); } internal BlockCaret( IVimBufferData vimBufferData, IClassificationFormatMap classificationFormatMap, IEditorFormatMap formatMap, IAdornmentLayer layer, IControlCharUtil controlCharUtil, IProtectedOperations protectedOperations) { _vimBufferData = vimBufferData; _textView = (IWpfTextView)_vimBufferData.TextView; _selectionUtil = _vimBufferData.SelectionUtil; _editorFormatMap = formatMap; _adornmentLayer = layer; _protectedOperations = protectedOperations; _classificationFormatMap = classificationFormatMap; _controlCharUtil = controlCharUtil; _textView.LayoutChanged += OnCaretEvent; _textView.GotAggregateFocus += OnCaretEvent; _textView.LostAggregateFocus += OnCaretEvent; _textView.Selection.SelectionChanged += OnCaretPositionOrSelectionChanged; _textView.Closed += OnTextViewClosed; _blinkTimer = CreateBlinkTimer(protectedOperations, OnCaretBlinkTimer); } internal BlockCaret( IVimBufferData vimBufferData, string adornmentLayerName, IClassificationFormatMap classificationFormatMap, IEditorFormatMap formatMap, IControlCharUtil controlCharUtil, IProtectedOperations protectedOperations) : this( vimBufferData, classificationFormatMap, formatMap, (vimBufferData.TextView as IWpfTextView).GetAdornmentLayer(adornmentLayerName), controlCharUtil, protectedOperations) { } /// <summary> /// Snap the specifed value to whole device pixels, optionally ensuring /// that the value is positive /// </summary> /// <param name="value"></param> /// <param name="ensurePositive"></param> /// <returns></returns> private double SnapToWholeDevicePixels(double value, bool ensurePositive) { var visualElement = _textView.VisualElement; var presentationSource = PresentationSource.FromVisual(visualElement); var matrix = presentationSource.CompositionTarget.TransformToDevice; var dpiFactor = 1.0 / matrix.M11; var wholePixels = Math.Round(value / dpiFactor); if (ensurePositive && wholePixels < 1.0) { wholePixels = 1.0; } return wholePixels * dpiFactor; } /// <summary> /// Get the number of milliseconds for the caret blink time. Null is returned if the /// caret should not blink /// </summary> private static int? GetCaretBlinkTime() { var blinkTime = NativeMethods.GetCaretBlinkTime(); // The API returns INFINITE if the caret simply should not blink. Additionally it returns // 0 on error which we will just treat as infinite if (blinkTime == NativeMethods.INFINITE || blinkTime == 0) { return null; } try { return checked((int)blinkTime); } catch (Exception) { return null; } } /// <summary> /// This helper is used to work around a reported, but unreproducable, bug. The constructor /// of DispatcherTimer is throwing an exception claiming a millisecond time greater /// than int.MaxValue is being passed to the constructor. /// /// This is clearly not possible given the input is an int value. However after multiple user /// reports it's clear the exception is getting triggered. /// /// The only semi-plausible idea I can come up with is a floating point conversion issue. Given /// that the input to Timespan is int and the compared value is double it's possible that a /// conversion / rounding issue is causing int.MaxValue to become int.MaxValue + 1. /// /// Either way though need to guard against this case to unblock users. /// /// https://github.com/VsVim/VsVim/issues/631 /// https://github.com/VsVim/VsVim/issues/1860 /// </summary> private static DispatcherTimer CreateBlinkTimer(IProtectedOperations protectedOperations, EventHandler onCaretBlinkTimer) { var caretBlinkTime = GetCaretBlinkTime(); var caretBlinkTimeSpan = new TimeSpan(0, 0, 0, 0, caretBlinkTime ?? int.MaxValue); try { var blinkTimer = new DispatcherTimer( caretBlinkTimeSpan, DispatcherPriority.Normal, protectedOperations.GetProtectedEventHandler(onCaretBlinkTimer), Dispatcher.CurrentDispatcher) { IsEnabled = caretBlinkTime != null }; return blinkTimer; } catch (ArgumentOutOfRangeException) { // Hit the bug ... just create a simple timer with a default interval. VimTrace.TraceError("Error creating BlockCaret DispatcherTimer"); var blinkTimer = new DispatcherTimer( TimeSpan.FromSeconds(2), DispatcherPriority.Normal, protectedOperations.GetProtectedEventHandler(onCaretBlinkTimer), Dispatcher.CurrentDispatcher) { IsEnabled = true }; return blinkTimer; } } private void OnCaretEvent(object sender, EventArgs e) { UpdateCaret(); } private void OnCaretBlinkTimer(object sender, EventArgs e) { foreach (var caretData in _caretDataMap.Values) { if (caretData.CaretDisplay != CaretDisplay.NormalCaret) { caretData.Element.Opacity = caretData.Element.Opacity == 0.0 ? 1.0 : 0.0; } } } /// <summary> /// Whenever the caret moves it should become both visible and reset /// the blink timer. This is the behavior of gVim. It can be /// demonstrated by simply moving the caret horizontally along a line /// of text. If the interval between the movement commands is shorter /// than the blink timer the caret will always be visible. Note that we /// use the selection changed event which is a superset of the caret /// position changed event and also includes any changes to secondary /// carets /// </summary> private void OnCaretPositionOrSelectionChanged(object sender, EventArgs e) { RestartBlinkCycle(); UpdateCaret(); } private void RestartBlinkCycle() { if (_blinkTimer.IsEnabled) { _blinkTimer.IsEnabled = false; _blinkTimer.IsEnabled = true; } // If the caret is invisible, make it visible foreach (var caretData in _caretDataMap.Values) { if (caretData.CaretDisplay != CaretDisplay.NormalCaret) { caretData.Element.Opacity = _caretOpacity; } } } private void OnTextViewClosed(object sender, EventArgs e) { _blinkTimer.IsEnabled = false; } private void OnBlockCaretAdornmentRemoved(object tag, UIElement element) { _adornmentsPresent.Remove(tag); } private void EnsureAdnormentsRemoved() { while (_adornmentsPresent.Count > 0) { var tag = _adornmentsPresent.First(); EnsureAdnormentRemoved(tag); } } private void EnsureAdnormentRemoved(object tag) { if (_adornmentsPresent.Contains(tag)) { _adornmentLayer.RemoveAdornmentsByTag(tag); Contract.Assert(!_adornmentsPresent.Contains(tag)); } } private string GetFormatName(int caretIndex, int numberOfCarets) { return numberOfCarets == 1 ? BlockCaretFormatDefinition.Name : (caretIndex == 0 ? PrimaryCaretFormatDefinition.Name : SecondaryCaretFormatDefinition.Name); } /// <summary> /// Attempt to copy the real caret color /// </summary> private Color? TryCalculateCaretColor(int caretIndex, int numberOfCarets) { var formatName = GetFormatName(caretIndex, numberOfCarets); const string key = EditorFormatDefinition.BackgroundColorId; var properties = _editorFormatMap.GetProperties(formatName); if (properties.Contains(key)) { return (Color)properties[key]; } return null; } private Point GetRealCaretVisualPoint(VirtualSnapshotPoint caretPoint) { // Default screen position is the same as that of the native caret. if (IsRealCaretVisible(caretPoint, out var textViewLine)) { var bounds = textViewLine.GetCharacterBounds(caretPoint); var left = bounds.Left; - var top = bounds.Top; + var top = bounds.TextTop; if (_caretDisplay == CaretDisplay.Block || _caretDisplay == CaretDisplay.HalfBlock || _caretDisplay == CaretDisplay.QuarterBlock) { var point = caretPoint.Position; if (point < _textView.TextSnapshot.Length && point.GetChar() == '\t') { // Any kind of block caret situated on a tab floats over // the last space occupied by the tab. var width = textViewLine.GetCharacterBounds(point).Width; var defaultWidth = _formattedText.Width; var offset = Math.Max(0, width - defaultWidth); left += offset; } } return new Point(left, top); } return s_invalidPoint; } private void MoveCaretElementToCaret(VirtualSnapshotPoint caretPoint, CaretData caretData) { var point = GetRealCaretVisualPoint(caretPoint); if (point == s_invalidPoint) { caretData.Element.Visibility = Visibility.Hidden; } else { caretData.Element.Visibility = Visibility.Visible; if (caretData.CaretDisplay == CaretDisplay.Select) { point = new Point(SnapToWholeDevicePixels(point.X, ensurePositive: false), point.Y); } Canvas.SetLeft(caretData.Element, point.X); Canvas.SetTop(caretData.Element, point.Y + caretData.YDisplayOffset); } } private FormattedText CreateFormattedText() { var textRunProperties = _classificationFormatMap.DefaultTextProperties; return new FormattedText("A", CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, textRunProperties.Typeface, textRunProperties.FontRenderingEmSize, Brushes.Black); } /// <summary> /// Calculate the dimensions of the caret /// </summary> private Size CalculateCaretSize(VirtualSnapshotPoint caretPoint, out string caretCharacter) { caretCharacter = ""; var defaultWidth = _formattedText.Width; var width = defaultWidth; var height = _textView.LineHeight; if (IsRealCaretVisible(caretPoint, out var textViewLine)) { // Get the caret height. height = textViewLine.TextHeight; // Try to use the same line height that a selection would use. var textViewLines = _textView.TextViewLines; if (textViewLines != null && textViewLines.IsValid) { var geometry = textViewLines.GetMarkerGeometry(textViewLine.Extent); if (geometry != null) { height = geometry.Bounds.Height; } } // Get the caret string and caret width. var point = caretPoint.Position; var codePointInfo = new SnapshotCodePoint(point).CodePointInfo; if (point.Position < point.Snapshot.Length) { var pointCharacter = point.GetChar(); if (_controlCharUtil.TryGetDisplayText(pointCharacter, out string caretString)) { // Handle control character notation. caretCharacter = caretString; width = textViewLine.GetCharacterBounds(point).Width; } else if (codePointInfo == CodePointInfo.SurrogatePairHighCharacter) { // Handle surrogate pairs. caretCharacter = new SnapshotSpan(point, 2).GetText(); width = textViewLine.GetCharacterBounds(point).Width; } else if (pointCharacter == '\t') { // Handle tab as no character and default width, // except no wider than the tab's screen width. caretCharacter = ""; width = Math.Min(defaultWidth, textViewLine.GetCharacterBounds(point).Width); } else if (pointCharacter == '\r' || pointCharacter == '\n') { // Handle linebreak. caretCharacter = ""; width = textViewLine.GetCharacterBounds(point).Width; } else { // Handle ordinary UTF16 character. caretCharacter = pointCharacter.ToString(); width = textViewLine.GetCharacterBounds(point).Width; } } } return new Size(width, height); } private double CalculateBaselineOffset(VirtualSnapshotPoint caretPoint) { var offset = 0.0; if (IsRealCaretVisible(caretPoint, out var textViewLine)) { offset = Math.Max(0.0, textViewLine.Baseline - _formattedText.Baseline); } return offset; } private Tuple<Rect, double, string> CalculateCaretRectAndDisplayOffset(VirtualSnapshotPoint caretPoint) { var size = CalculateCaretSize(caretPoint, out string caretCharacter); var point = GetRealCaretVisualPoint(caretPoint); var blockPoint = point; switch (_caretDisplay) { case CaretDisplay.Block: break; case CaretDisplay.HalfBlock: size = new Size(size.Width, size.Height / 2); blockPoint = new Point(blockPoint.X, blockPoint.Y + size.Height); break; case CaretDisplay.QuarterBlock: size = new Size(size.Width, size.Height / 4); blockPoint = new Point(blockPoint.X, blockPoint.Y + 3 * size.Height); break; case CaretDisplay.Select: caretCharacter = null; var width = SnapToWholeDevicePixels(_textView.Caret.Width, ensurePositive: true); var height = _textView.Caret.Height; size = new Size(width, height); break; case CaretDisplay.Invisible: case CaretDisplay.NormalCaret: caretCharacter = null; size = new Size(0, 0); break; default: throw new InvalidOperationException("Invalid enum value"); } var rect = new Rect(blockPoint, size); var offset = blockPoint.Y - point.Y; return Tuple.Create(rect, offset, caretCharacter); } private CaretData CreateCaretData(int caretIndex, int numberOfCarets) { var caretPoint = _caretPoints[caretIndex]; _formattedText = CreateFormattedText(); var color = TryCalculateCaretColor(caretIndex, numberOfCarets); var tuple = CalculateCaretRectAndDisplayOffset(caretPoint); var baselineOffset = CalculateBaselineOffset(caretPoint); var rect = tuple.Item1; var width = rect.Size.Width; var height = rect.Size.Height; var offset = tuple.Item2; var caretCharacter = tuple.Item3; var formatName = GetFormatName(caretIndex, numberOfCarets); var properties = _editorFormatMap.GetProperties(formatName); var foregroundBrush = properties.GetForegroundBrush(SystemColors.WindowBrush); var backgroundBrush = properties.GetBackgroundBrush(SystemColors.WindowTextBrush); var textRunProperties = _classificationFormatMap.DefaultTextProperties; var typeface = textRunProperties.Typeface; var fontSize = textRunProperties.FontRenderingEmSize; var textHeight = offset + height; var lineHeight = _textView.LineHeight; if (_caretOpacity < 1.0 && backgroundBrush is SolidColorBrush solidBrush) { var alpha = (byte)Math.Round(0xff * _caretOpacity); var oldColor = solidBrush.Color; var newColor = Color.FromArgb(alpha, oldColor.R, oldColor.G, oldColor.B); backgroundBrush = new SolidColorBrush(newColor); } var rectangle = new Rectangle { Width = width, Height = baselineOffset, Fill = backgroundBrush, }; var textBlock = new TextBlock { Text = caretCharacter, Foreground = foregroundBrush, Background = backgroundBrush, FontFamily = typeface.FontFamily, FontStretch = typeface.Stretch, FontWeight = typeface.Weight, FontStyle = typeface.Style, FontSize = fontSize, Width = width, Height = textHeight, LineHeight = lineHeight, }; var element = new Canvas { Width = width, Height = height, ClipToBounds = true, Children = { rectangle, textBlock, }, }; Canvas.SetTop(rectangle, -offset); Canvas.SetLeft(textBlock, 0); Canvas.SetTop(textBlock, -offset + baselineOffset); Canvas.SetLeft(textBlock, 0); return new CaretData( caretIndex, _caretDisplay, _caretOpacity, element, color, rect.Size, offset, baselineOffset, caretCharacter); } /// <summary> /// This determines if the image which is used to represent the caret is stale and needs /// to be recreated. /// </summary> private bool IsAdornmentStale(VirtualSnapshotPoint caretPoint, CaretData caretData, int numberOfCarets) { // Size is represented in floating point so strict equality comparison will almost // always return false. Use a simple epsilon to test the difference if (caretData.Color != TryCalculateCaretColor(caretData.CaretIndex, numberOfCarets) || caretData.CaretDisplay != _caretDisplay || caretData.CaretOpacity != _caretOpacity) { return true; } var tuple = CalculateCaretRectAndDisplayOffset(caretPoint); var epsilon = 0.001; var size = tuple.Item1.Size; if (Math.Abs(size.Height - caretData.Size.Height) > epsilon || Math.Abs(size.Width - caretData.Size.Width) > epsilon) { return true; } var caretCharacter = tuple.Item3; if (caretData.CaretCharacter != caretCharacter) { return true; } return false; } private void EnsureCaretDisplayed() { // For normal caret we just use the standard caret. Make sure the adornment is removed and // let the normal caret win if (CaretDisplay == CaretDisplay.NormalCaret) { EnsureAdnormentsRemoved(); _textView.Caret.IsHidden = false; return; } _textView.Caret.IsHidden = true; var numberOfCarets = _caretPoints.Count; for (var caretIndex = 0; caretIndex < numberOfCarets; caretIndex++) { if (caretIndex == _tags.Count) { _tags.Add(new object()); } var tag = _tags[caretIndex]; var caretPoint = _caretPoints[caretIndex]; if (_caretDataMap.TryGetValue(caretIndex, out CaretData value)) { if (IsAdornmentStale(caretPoint, value, numberOfCarets)) { EnsureAdnormentRemoved(tag); _caretDataMap[caretIndex] = CreateCaretData(caretIndex, numberOfCarets); } } else { _caretDataMap[caretIndex] = CreateCaretData(caretIndex, numberOfCarets); } var caretData = _caretDataMap[caretIndex]; MoveCaretElementToCaret(caretPoint, caretData); if (!_adornmentsPresent.Contains(tag)) { var adornmentAdded = _adornmentLayer.AddAdornment( AdornmentPositioningBehavior.TextRelative, new SnapshotSpan(caretPoint.Position, 0), tag, caretData.Element, OnBlockCaretAdornmentRemoved); if (adornmentAdded) { _adornmentsPresent.Add(tag); } } } while (_caretDataMap.Count > numberOfCarets) { var caretIndex = _caretDataMap.Count - 1; EnsureAdnormentRemoved(_tags[caretIndex]); _caretDataMap.Remove(caretIndex); } // When the caret display is changed (e.g. from normal to block) we // need to restart the blink cycle so that the caret is immediately // visible. Reported in issue #2301. RestartBlinkCycle(); } private void UpdateCaret() { if (_isUpdating) { return; } _isUpdating = true; try { UpdateCaretCore(); } finally { _isUpdating = false; } } private void UpdateCaretCore() { if (_selectionUtil.IsMultiSelectionSupported) { _caretPoints = _selectionUtil.GetSelectedSpans() .Select(span => span.CaretPoint) .ToList(); } else { _caretPoints = new List<VirtualSnapshotPoint> { _textView.Caret.Position.VirtualBufferPosition }; } var areAnyCaretsVisible = _caretPoints .Select(caretPoint => IsRealCaretVisible(caretPoint)) .Any(isVisible => isVisible); if (!areAnyCaretsVisible) { EnsureAdnormentsRemoved(); } else { EnsureCaretDisplayed(); } } /// <summary> /// Destroy all of the caret related data such that the caret is free for collection. In particular /// make sure to disable the DispatchTimer as keeping it alive will prevent collection /// </summary> private void DestroyCore() { _isDestroyed = true; _blinkTimer.IsEnabled = false; EnsureAdnormentsRemoved(); if (!_textView.IsClosed) { _textView.LayoutChanged -= OnCaretEvent; _textView.GotAggregateFocus -= OnCaretEvent; _textView.LostAggregateFocus -= OnCaretEvent; _textView.Selection.SelectionChanged -= OnCaretPositionOrSelectionChanged; _textView.Caret.IsHidden = false; _textView.Closed -= OnTextViewClosed; } } private void MaybeDestroy() { if (!_isDestroyed) { DestroyCore(); } } public void Destroy() { MaybeDestroy(); } } }
VsVim/VsVim
bcc6cb780b5bae1562494a54e0210513a2ae14ff
Delete a collapsed region correctly.
diff --git a/Src/VimCore/CommonOperations.fs b/Src/VimCore/CommonOperations.fs index aa2baf5..ec5892d 100644 --- a/Src/VimCore/CommonOperations.fs +++ b/Src/VimCore/CommonOperations.fs @@ -293,1060 +293,1062 @@ type internal CommonOperations member x.GetSpacesToVirtualColumnNumber line columnNumber = VirtualSnapshotColumn.GetSpacesToColumnNumber(line, columnNumber, _localSettings.TabStop) // Get the virtual point in the given line which is count "spaces" into the line. Returns End if // it goes beyond the last point in the string member x.GetVirtualColumnForSpaces line spaces = VirtualSnapshotColumn.GetColumnForSpaces(line, spaces, _localSettings.TabStop) // Get the appropriate column for spaces on the specified line depending on // whether virtual space is in effect member x.GetAppropriateColumnForSpaces line spaces = if _vimTextBuffer.UseVirtualSpace then x.GetVirtualColumnForSpaces line spaces else x.GetColumnForSpacesOrEnd line spaces |> VirtualSnapshotColumn /// Get the new line text which should be used for inserts at the provided point. This is done /// by looking at the current line and potentially the line above and simply re-using it's /// value member x.GetNewLineText point = if not (_editorOptions.GetReplicateNewLineCharacter()) then // If we're not supposed to replicate the current new line character then just go ahead // and use the default new line character (so odd they call it character when it's // by default 2 characters) _editorOptions.GetNewLineCharacter() else let line = SnapshotPointUtil.GetContainingLine point let line = // If this line has no line break, use the line above let snapshot = point.Snapshot if not (SnapshotLineUtil.HasLineBreak line) && line.LineNumber > 0 then SnapshotUtil.GetLine snapshot (line.LineNumber - 1) else line if line.LineBreakLength > 0 then line.GetLineBreakText() else _editorOptions.GetNewLineCharacter() /// In order for Undo / Redo to function properly there needs to be an ITextView for the ITextBuffer /// accessible in the property bag of the ITextUndoHistory object. In 2017 and before this was added /// during AfterTextBufferChangeUndoPrimitive.Create. In 2019 this stopped happening and hence undo / /// redo is broken. Forcing it to be present here. /// https://github.com/VsVim/VsVim/issues/2463 member x.EnsureUndoHasView() = match _undoRedoOperations.TextUndoHistory with | None -> () | Some textUndoHistory -> let key = typeof<ITextView> let properties = textUndoHistory.Properties if not (PropertyCollectionUtil.ContainsKey key properties) then properties.AddProperty(key, _textView) // Convert any virtual spaces to real normalized spaces member x.FillInVirtualSpace () = // This is an awkward situation if 'expandtab' is in effect because // Visual Studio uses tabs when filling in virtual space, but vim // doesn't. VsVim needs to insert tabs when filling in leading virtual // space to emulate the way vim copies leading tabs from surrounding // lines, but shouldn't insert tabs when filling in non-leading virtual // space because vim never inserts tabs in that situation. if x.CaretVirtualPoint.IsInVirtualSpace then let blanks: string = let blanks = StringUtil.RepeatChar x.CaretVirtualColumn.VirtualSpaces ' ' if x.CaretPoint = x.CaretLine.Start then // The line is completely empty so use tabs if appropriate. let spacesToColumn = x.GetSpacesToPoint x.CaretPoint x.NormalizeBlanks blanks spacesToColumn else blanks // Make sure to position the caret to the end of the newly inserted spaces let position = x.CaretColumn.StartPosition + blanks.Length _textBuffer.Insert(x.CaretColumn.StartPosition, blanks) |> ignore TextViewUtil.MoveCaretToPosition _textView position /// Filter the specified line range through the specified program member x.FilterLines (range: SnapshotLineRange) program = // Extract the lines to be filtered. let newLine = EditUtil.NewLine _editorOptions _textBuffer let input = range.Lines |> Seq.map SnapshotLineUtil.GetText |> Seq.map (fun line -> line + newLine) |> String.concat StringUtil.Empty // Filter the input to the output. let workingDirectory = _vimBufferData.WorkingDirectory let shell = _globalSettings.Shell let results = _vimHost.RunCommand workingDirectory shell program input // Display error output and error code, if any. let error = results.Error let error = if results.ExitCode <> 0 then let message = Resources.Filter_CommandReturned results.ExitCode message + newLine + error else error let error = EditUtil.RemoveEndingNewLine error _statusUtil.OnStatus error // Prepare the replacement. let replacement = results.Output if replacement.Length = 0 then // Forward to delete lines to handle special cases. let startLine = range.StartLine let count = range.Count let registerName = None x.DeleteLines startLine count registerName else // Remove final linebreak. let replacement = EditUtil.RemoveEndingNewLine replacement // Normalize linebreaks. let replacement = EditUtil.NormalizeNewLines replacement newLine // Replace the old lines with the filtered lines. _textBuffer.Replace(range.Extent.Span, replacement) |> ignore // Place the cursor on the first non-blank character of the first line filtered. let firstLine = SnapshotUtil.GetLine _textView.TextSnapshot range.StartLineNumber TextViewUtil.MoveCaretToPoint _textView firstLine.Start _editorOperations.MoveToStartOfLineAfterWhiteSpace(false) /// Format the code lines in the specified line range member x.FormatCodeLines range = _vimHost.FormatLines _textView range // Place the cursor on the first non-blank character of the first line formatted. let firstLine = SnapshotUtil.GetLine _textView.TextSnapshot range.StartLineNumber TextViewUtil.MoveCaretToPoint _textView firstLine.Start _editorOperations.MoveToStartOfLineAfterWhiteSpace(false) /// Format the text lines in the specified line range member x.FormatTextLines (range: SnapshotLineRange) preserveCaretPosition = // Get formatting configuration values. let autoIndent = _localSettings.AutoIndent let textWidth = if _localSettings.TextWidth = 0 then VimConstants.DefaultFormatTextWidth else _localSettings.TextWidth let comments = _localSettings.Comments let tabStop = _localSettings.TabStop // Extract the lines to be formatted and the first line. let lines = range.Lines |> Seq.map SnapshotLineUtil.GetText let firstLine = lines |> Seq.head // Extract the leader string from a comment specification, e.g. "//". let getLeaderFromSpec (spec: string) = let colonIndex = spec.IndexOf(':') if colonIndex = -1 then spec else spec.Substring(colonIndex + 1) // Get the leader pattern for a leader string. let getLeaderPattern (leader: string) = if leader = "" then @"^\s*" else @"^\s*" + Regex.Escape(leader) + @"+\s*" // Convert the comment specifications into leader patterns. let patterns = comments + ",:" |> StringUtil.Split ',' |> Seq.map getLeaderFromSpec |> Seq.map getLeaderPattern // Check the first line against a potential comment pattern. let checkPattern pattern = let capture = Regex.Match(firstLine, pattern) if capture.Success then true, pattern, capture.Value else false, pattern, "" // Choose a pattern and a leader. let _, pattern, leader = patterns |> Seq.map checkPattern |> Seq.filter (fun (matches, _, _) -> matches) |> Seq.head // Decide whether to use the leader for all lines. let useLeaderForAllLines = not (StringUtil.IsWhiteSpace leader) || autoIndent // Strip the leader from a line. let stripLeader (line: string) = let capture = Regex.Match(line, pattern) if capture.Success then line.Substring(capture.Length) else line // Strip the leader from all the lines. let strippedLines = lines |> Seq.map stripLeader // Split a line into words on whitespace. let splitWords (line: string) = if StringUtil.IsWhiteSpace line then seq { yield "" } else Regex.Matches(line + " ", @"\S+\s+") |> Seq.cast<Capture> |> Seq.map (fun capture -> capture.Value) // Concatenate a reversed list of words into a line. let concatWords (words: string list) = words |> Seq.rev |> String.concat "" |> (fun line -> line.TrimEnd()) // Concatenate words into a line and prepend it to a list of lines. let prependLine (words: string list) (lines: string list) = if words.IsEmpty then lines else concatWords words :: lines // Calculate the length of the leader with tabs expanded. let leaderLength = StringUtil.ExpandTabsForColumn leader 0 tabStop |> StringUtil.GetLength // Aggregrate individual words into lines of limited length. let takeWord ((column: int), (words: string list), (lines: string list)) (word: string) = // Calculate the working limit for line length. let limit = if lines.IsEmpty || useLeaderForAllLines then textWidth - leaderLength else textWidth if word = "" then 0, List.Empty, "" :: prependLine words lines elif column = 0 || column + word.TrimEnd().Length <= limit then column + word.Length, word :: words, lines else word.Length, word :: List.Empty, concatWords words :: lines // Add a leader to the formatted line if appropriate. let addLeader (i: int) (line: string) = if i = 0 || useLeaderForAllLines then (leader + line).TrimEnd() else line // Split the lines into words and then format them into lines using the aggregator. let formattedLines = let _, words, lines = strippedLines |> Seq.collect splitWords |> Seq.fold takeWord (0, List.Empty, List.Empty) prependLine words lines |> Seq.rev |> Seq.mapi addLeader // Concatenate the formatted lines. let newLine = EditUtil.NewLine _editorOptions _textBuffer let replacement = formattedLines |> String.concat newLine // Replace the old lines with the formatted lines. _textBuffer.Replace(range.Extent.Span, replacement) |> ignore // Place the cursor on the first non-blank character of the first line formatted. let firstLine = SnapshotUtil.GetLine _textView.TextSnapshot range.StartLineNumber TextViewUtil.MoveCaretToPoint _textView firstLine.Start _editorOperations.MoveToStartOfLineAfterWhiteSpace(false) /// The caret sometimes needs to be adjusted after an Up or Down movement. Caret position /// and virtual space is actually quite a predicament for VsVim because of how Vim standard /// works. Vim has no concept of Virtual Space and is designed to work in a fixed width /// font buffer. Visual Studio has essentially the exact opposite. Non-fixed width fonts are /// the most problematic because it makes the natural Vim motion of column based up and down /// make little sense visually. Instead we rely on the core editor for up and down motions. /// /// The two exceptions to this are the Virtual Edit and exclusive setting in Visual Mode. By /// default the 'l' motion will only move you to the last character on the line and no /// further. Visual Studio up and down though acts like virtualedit=onemore. We correct /// this here member x.AdjustCaretForVirtualEdit() = // Vim allows the caret past the end of the line if we are in a // one-time command and returning to insert mode momentarily. let allowPastEndOfLine = _vimTextBuffer.ModeKind = ModeKind.Insert || _globalSettings.IsVirtualEditOneMore || VisualKind.IsAnySelect _vimTextBuffer.ModeKind || _vimTextBuffer.InOneTimeCommand.IsSome if not allowPastEndOfLine && not (VisualKind.IsAnyVisual _vimTextBuffer.ModeKind) then let column = TextViewUtil.GetCaretColumn _textView let line = column.Line if column.StartPosition >= line.End.Position && line.Length > 0 then let column = column.SubtractOrStart 1 TextViewUtil.MoveCaretToColumn _textView column /// Adjust the ITextView scrolling to account for the 'scrolloff' setting after a move operation /// completes member x.AdjustTextViewForScrollOffset() = x.AdjustTextViewForScrollOffsetAtPoint x.CaretPoint member x.AdjustTextViewForScrollOffsetAtPoint point = if _globalSettings.ScrollOffset > 0 then x.AdjustTextViewForScrollOffsetAtPointCore point _globalSettings.ScrollOffset /// The most efficient API for moving the scroll is DisplayTextLineContainingBufferPosition. This is actually /// what the scrolling APIs use to implement scrolling. Unfortunately this API deals is in buffer positions /// but we want to scroll visually. /// /// This is easier to explain with folding. If the line just above the caret is 300 lines folded into 1 then /// we want to consider only the folded line for scroll offset, not the 299 invisible lines. In order to do /// this we need to map the caret position up to the visual buffer, do the line math there, find the correct /// visual line, then map the start of that line back down to the edit buffer. /// /// This function also suffers from another problem. The font in Visual Studio is not guaranteed to be fixed /// width / height. Adornments can also cause lines to be taller or shorter than they should be. Hence we /// have to approximate the number of lines that can be on the screen in order to calculate the proper /// offset to use. member x.AdjustTextViewForScrollOffsetAtPointCore contextPoint offset = Contract.Requires(offset > 0) // If the text view is still being initialized, the viewport will have zero height // which will force offset to zero. Likewise, if there are no text view lines, // trying to scroll is pointless. match _textView.ViewportHeight, TextViewUtil.GetTextViewLines _textView with | height, Some textViewLines when height <> 0.0 && textViewLines.Count <> 0 -> // First calculate the actual offset. The actual offset can't be more than half of the lines which // are visible on the screen. It's tempting to use the ITextViewLinesCollection.Count to see how // many possible lines are displayed. This value will be wrong though when the view is scrolled // to the bottom because it will be displaying the last few lines and several blanks which don't // count. Instead we average out the height of the lines and divide that into the height of // the view port let offset = let lineHeight = textViewLines |> Seq.averageBy (fun l -> l.Height) let lineCount = int (_textView.ViewportHeight / lineHeight) let maxOffset = lineCount / 2 min maxOffset offset // This function will do the actual positioning of the scroll based on the calculated lines // in the buffer let doScroll topPoint bottomPoint = let firstVisibleLineNumber = SnapshotPointUtil.GetLineNumber textViewLines.FirstVisibleLine.Start let lastVisibleLineNumber = SnapshotPointUtil.GetLineNumber textViewLines.LastVisibleLine.End let topLineNumber = SnapshotPointUtil.GetLineNumber topPoint let bottomLineNumber = SnapshotPointUtil.GetLineNumber bottomPoint if topLineNumber < firstVisibleLineNumber then _textView.DisplayTextLineContainingBufferPosition(topPoint, 0.0, ViewRelativePosition.Top) elif bottomLineNumber > lastVisibleLineNumber then _textView.DisplayTextLineContainingBufferPosition(bottomPoint, 0.0, ViewRelativePosition.Bottom) // Time to map up and down the buffer graph to find the correct top and bottom point that the scroll // needs tobe adjusted to let visualSnapshot = _textView.VisualSnapshot let editSnapshot = _textView.TextSnapshot match BufferGraphUtil.MapPointUpToSnapshotStandard _textView.BufferGraph contextPoint visualSnapshot with | None -> () | Some visualPoint -> let visualLine = SnapshotPointUtil.GetContainingLine visualPoint let visualLineNumber = visualLine.LineNumber // Calculate the line information in the visual buffer let topLineNumber = max 0 (visualLineNumber - offset) let bottomLineNumber = min (visualLineNumber + offset) (visualSnapshot.LineCount - 1) let visualTopLine = SnapshotUtil.GetLine visualSnapshot topLineNumber let visualBottomLine = SnapshotUtil.GetLine visualSnapshot bottomLineNumber // Map it back down to the edit buffer and then scroll let editTopPoint = BufferGraphUtil.MapPointDownToSnapshotStandard _textView.BufferGraph visualTopLine.Start editSnapshot let editBottomPoint = BufferGraphUtil.MapPointDownToSnapshotStandard _textView.BufferGraph visualBottomLine.Start editSnapshot match editTopPoint, editBottomPoint with | Some p1, Some p2 -> doScroll p1 p2 | _ -> () | _ -> () /// This is the same function as AdjustTextViewForScrollOffsetAtPoint except that it moves the caret /// not the view port. Make the caret consistent with the setting not the display /// /// Once again we are dealing with visual lines, not buffer lines member x.AdjustCaretForScrollOffset () = match TextViewUtil.GetTextViewLines _textView with | None -> () | Some textViewLines -> // This function will do the actual caret positioning based on the top visual and bottom // visual line. The return will be the position within the visual buffer, not the edit // buffer let getLinePosition caretLineNumber topLineNumber bottomLineNumber = if _globalSettings.ScrollOffset <= 0 || _globalSettings.ScrollOffset * 2 >= (bottomLineNumber - topLineNumber) then None elif caretLineNumber < (topLineNumber + _globalSettings.ScrollOffset) || caretLineNumber > (bottomLineNumber - _globalSettings.ScrollOffset) then let lineNumber = caretLineNumber let topOffset = min caretLineNumber _globalSettings.ScrollOffset let lastVisualLineNumber = _textView.VisualSnapshot.LineCount - 1 let bottomOffset = min (lastVisualLineNumber - caretLineNumber) _globalSettings.ScrollOffset let lineNumber = max lineNumber (topLineNumber + topOffset) let lineNumber = min lineNumber (bottomLineNumber - bottomOffset) if lineNumber <> caretLineNumber then Some lineNumber else None else None let visualSnapshot = _textView.VisualSnapshot let editSnapshot = _textView.TextSnapshot let bufferGraph = _textView.BufferGraph let topVisualPoint = BufferGraphUtil.MapPointUpToSnapshotStandard bufferGraph textViewLines.FirstVisibleLine.Start visualSnapshot let bottomVisualPoint = BufferGraphUtil.MapPointUpToSnapshotStandard bufferGraph textViewLines.LastVisibleLine.Start visualSnapshot let caretVisualPoint = BufferGraphUtil.MapPointUpToSnapshotStandard bufferGraph x.CaretPoint visualSnapshot match topVisualPoint, bottomVisualPoint, caretVisualPoint with | Some topVisualPoint, Some bottomVisualPoint, Some caretVisualPoint -> let topLineNumber = SnapshotPointUtil.GetLineNumber topVisualPoint let bottomLineNumber = SnapshotPointUtil.GetLineNumber bottomVisualPoint let caretLineNumber = SnapshotPointUtil.GetLineNumber caretVisualPoint match getLinePosition caretLineNumber topLineNumber bottomLineNumber with | Some visualLineNumber -> let visualLine = visualSnapshot.GetLineFromLineNumber visualLineNumber match BufferGraphUtil.MapPointDownToSnapshotStandard bufferGraph visualLine.Start editSnapshot with | Some editPoint -> x.MoveCaretToLine (editPoint.GetContainingLine()) | None -> () | None -> () | _ -> () /// This method is used to essentially find a line in the edit buffer which represents /// the start of a visual line. The context provided is a line in the edit buffer /// which maps to some point on that visual line. /// /// This is needed in outlining cases where a visual line has a different edit line /// at the start and line break of the visual line. The function will map the line at the /// line break back to the line of the start. member x.AdjustEditLineForVisualSnapshotLine (line: ITextSnapshotLine) = let bufferGraph = _textView.BufferGraph let visualSnapshot = _textView.TextViewModel.VisualBuffer.CurrentSnapshot match BufferGraphUtil.MapSpanUpToSnapshot bufferGraph line.ExtentIncludingLineBreak SpanTrackingMode.EdgeInclusive visualSnapshot with | None -> line | Some col -> if col.Count = 0 then line else let span = NormalizedSnapshotSpanCollectionUtil.GetOverarchingSpan col span.Start.GetContainingLine() /// Delete count lines from the the specified line. The caret should be /// positioned on the first line for both undo / redo member x.DeleteLines (startLine: ITextSnapshotLine) count registerName = // Function to actually perform the delete let doDelete spanOnVisualSnapshot caretPointOnVisualSnapshot includesLastLine = // Make sure to map the SnapshotSpan back into the text / edit // buffer. let span = BufferGraphUtil.MapSpanDownToSingle _bufferGraph spanOnVisualSnapshot x.CurrentSnapshot let point = BufferGraphUtil.MapPointDownToSnapshotStandard _bufferGraph caretPointOnVisualSnapshot x.CurrentSnapshot match span, point with | Some span, Some caretPoint -> // Use a transaction to properly position the caret for undo / // redo. We want it in the same place for undo / redo so move // it before the transaction. let spaces = x.GetSpacesToCaret() TextViewUtil.MoveCaretToPoint _textView span.Start x.RestoreSpacesToCaret spaces true _undoRedoOperations.EditWithUndoTransaction "Delete Lines" _textView (fun () -> _textBuffer.Delete(span.Span) |> ignore // After delete the caret should move to the line of the // same number. SnapshotPointUtil.GetLineNumber caretPoint |> SnapshotUtil.GetLineOrLast x.CurrentSnapshot |> (fun line -> TextViewUtil.MoveCaretToPoint _textView line.Start) x.RestoreSpacesToCaret spaces true) // Need to manipulate the StringData so that it includes the expected trailing newline let stringData = if includesLastLine then let newLineText = x.GetNewLineText x.CaretPoint (span.GetText()) + newLineText |> EditUtil.RemoveBeginingNewLine |> StringData.Simple else span |> StringData.OfSpan // Now update the register after the delete completes let value = x.CreateRegisterValue x.CaretPoint stringData OperationKind.LineWise x.SetRegisterValue registerName RegisterOperation.Delete value | _ -> // If we couldn't map back down raise an error _statusUtil.OnError Resources.Internal_ErrorMappingToVisual - // First we need to remap the 'startLine' value. To do the delete we need to know the - // correct start line in the edit buffer. What we are provided is a value in the edit + // First we need to remap the 'startLine','count' value. To do the delete we need to know the + // correct start line and line count in the edit buffer. What we are provided is a value in the edit // buffer but it may be a line further down in the buffer due to folding. + let range = SnapshotLineRangeUtil.CreateForLineAndMaxCount startLine count + let lastLine = x.AdjustEditLineForVisualSnapshotLine range.LastLine let startLine = x.AdjustEditLineForVisualSnapshotLine startLine + let count = lastLine.LineNumber - startLine.LineNumber + 1 // The span should be calculated using the visual snapshot if available. Binding // it as 'x' here will help prevent us from accidentally mixing the visual and text // snapshot values let x = TextViewUtil.GetVisualSnapshotDataOrEdit _textView // Map the start line into the visual snapshot match BufferGraphUtil.MapPointUpToSnapshotStandard _bufferGraph startLine.Start x.CurrentSnapshot with | None -> // If we couldn't map back down raise an error _statusUtil.OnError Resources.Internal_ErrorMappingToVisual | Some point -> // Calculate the range in the visual snapshot let range = let line = SnapshotPointUtil.GetContainingLine point SnapshotLineRangeUtil.CreateForLineAndMaxCount line count // The last line without a line break is an unfortunate special case. Hence // in order to delete the line we must delete the line break at the end of the preceding line. // // This cannot be normalized by always deleting the line break from the previous line because // it would still break for the first line. This is an unfortunate special case we must // deal with let lastLineHasLineBreak = SnapshotLineUtil.HasLineBreak range.LastLine if not lastLineHasLineBreak && range.StartLineNumber > 0 then let aboveLine = SnapshotUtil.GetLine x.CurrentSnapshot (range.StartLineNumber - 1) let span = SnapshotSpan(aboveLine.End, range.End) doDelete span range.StartLine.Start true else // Simpler case. Get the line range and delete - let stringData = range.ExtentIncludingLineBreak |> StringData.OfSpan doDelete range.ExtentIncludingLineBreak range.StartLine.Start false /// Move the caret in the given direction member x.MoveCaret caretMovement = /// Move the caret to the same virtual position in line as the current caret line let moveToLineVirtual (line: ITextSnapshotLine) = if _vimTextBuffer.UseVirtualSpace then let caretPoint = x.CaretVirtualPoint let tabStop = _localSettings.TabStop let currentSpaces = VirtualSnapshotPointUtil.GetSpacesToPoint caretPoint tabStop let lineSpaces = SnapshotPointUtil.GetSpacesToPoint line.End tabStop if lineSpaces < currentSpaces then let virtualSpaces = currentSpaces - lineSpaces line.End |> VirtualSnapshotPointUtil.OfPoint |> VirtualSnapshotPointUtil.AddOnSameLine virtualSpaces |> (fun point -> x.MoveCaretToVirtualPoint point ViewFlags.Standard) true else false else false /// Move the caret up let moveUp () = match SnapshotUtil.TryGetLine x.CurrentSnapshot (x.CaretLine.LineNumber - 1) with | None -> false | Some line -> if not (moveToLineVirtual line) then _editorOperations.MoveLineUp(false) true /// Move the caret down let moveDown () = match SnapshotUtil.TryGetLine x.CurrentSnapshot (x.CaretLine.LineNumber + 1) with | None -> false | Some line -> if SnapshotLineUtil.IsPhantomLine line then false else if not (moveToLineVirtual line) then _editorOperations.MoveLineDown(false) true /// Move the caret left. Don't go past the start of the line let moveLeft () = match x.CaretColumn.TrySubtractInLine 1 with | Some column -> x.MoveCaretToPoint column.StartPoint ViewFlags.Standard true | None -> false /// Move the caret right. Don't go off the end of the line let moveRight () = match x.CaretColumn.TryAddInLine(1, includeLineBreak = true) with | Some column -> x.MoveCaretToPoint column.StartPoint ViewFlags.Standard true | None -> false let moveHome () = _editorOperations.MoveToStartOfLine(false) true let moveEnd () = _editorOperations.MoveToEndOfLine(false) true let movePageUp () = _editorOperations.PageUp(false) true let movePageDown () = _editorOperations.PageDown(false) true let moveControlUp () = moveUp() let moveControlDown () = moveDown() let moveControlLeft () = _editorOperations.MoveToPreviousWord(false) true let moveControlRight () = _editorOperations.MoveToNextWord(false) true let moveControlHome () = _editorOperations.MoveToStartOfDocument(false) true let moveControlEnd () = _editorOperations.MoveToEndOfDocument(false) true match caretMovement with | CaretMovement.Up -> moveUp() | CaretMovement.Down -> moveDown() | CaretMovement.Left -> moveLeft() | CaretMovement.Right -> moveRight() | CaretMovement.Home -> moveHome() | CaretMovement.End -> moveEnd() | CaretMovement.PageUp -> movePageUp() | CaretMovement.PageDown -> movePageDown() | CaretMovement.ControlUp -> moveControlUp() | CaretMovement.ControlDown -> moveControlDown() | CaretMovement.ControlLeft -> moveControlLeft() | CaretMovement.ControlRight -> moveControlRight() | CaretMovement.ControlHome -> moveControlHome() | CaretMovement.ControlEnd -> moveControlEnd() /// Move the caret in the given direction with an arrow key member x.MoveCaretWithArrow caretMovement = /// Move left one character taking into account 'whichwrap' let moveLeft () = let caretPoint = x.CaretVirtualPoint if _vimTextBuffer.UseVirtualSpace && caretPoint.IsInVirtualSpace then caretPoint |> VirtualSnapshotPointUtil.SubtractOneOrCurrent |> (fun point -> x.MoveCaretToVirtualPoint point ViewFlags.Standard) true elif _globalSettings.IsWhichWrapArrowLeftInsert then if SnapshotPointUtil.IsStartPoint x.CaretPoint then false else let point = SnapshotPointUtil.GetPreviousCharacterSpanWithWrap x.CaretPoint x.MoveCaretToPoint point ViewFlags.Standard true else x.MoveCaret caretMovement /// Move right one character taking into account 'whichwrap' let moveRight () = let caretPoint = x.CaretVirtualPoint if _vimTextBuffer.UseVirtualSpace && caretPoint.Position = x.CaretLine.End then caretPoint |> VirtualSnapshotPointUtil.AddOneOnSameLine |> (fun point -> x.MoveCaretToVirtualPoint point ViewFlags.Standard) true elif _globalSettings.IsWhichWrapArrowRightInsert then if SnapshotPointUtil.IsEndPoint x.CaretPoint then false else let point = SnapshotPointUtil.GetNextCharacterSpanWithWrap x.CaretPoint x.MoveCaretToPoint point ViewFlags.Standard true else x.MoveCaret caretMovement match caretMovement with | CaretMovement.Left -> moveLeft() | CaretMovement.Right -> moveRight() | _ -> x.MoveCaret caretMovement member x.MoveCaretToColumn (point: SnapshotColumn) viewFlags = x.MoveCaretToPoint point.StartPoint viewFlags member x.MoveCaretToVirtualColumn (point: VirtualSnapshotColumn) viewFlags = x.MoveCaretToVirtualPoint point.VirtualStartPoint viewFlags /// Move the caret to the specified point with the specified view properties member x.MoveCaretToPoint (point: SnapshotPoint) viewFlags = let virtualPoint = VirtualSnapshotPointUtil.OfPoint point x.MoveCaretToVirtualPoint virtualPoint viewFlags /// Move the caret to the specified virtual point with the specified view properties member x.MoveCaretToVirtualPoint (point: VirtualSnapshotPoint) viewFlags = // In the case where we want to expand the text we are moving to we need to do the expansion // first before the move. Before the text is expanded the point we are moving to will map to // the collapsed region. When the text is subsequently expanded it has no memory and will // just stay in place. if Util.IsFlagSet viewFlags ViewFlags.TextExpanded then x.EnsurePointExpanded point.Position TextViewUtil.MoveCaretToVirtualPoint _textView point x.EnsureAtPoint point.Position viewFlags /// Move the caret to the specified line maintaining it's current column member x.MoveCaretToLine line = let spaces = x.CaretColumn.GetSpacesToColumn _localSettings.TabStop let column = SnapshotColumn.GetColumnForSpacesOrEnd(line, spaces, _localSettings.TabStop) TextViewUtil.MoveCaretToColumn _textView column x.MaintainCaretColumn <- MaintainCaretColumn.Spaces spaces /// Move the caret to the position dictated by the given MotionResult value member x.MoveCaretToMotionResult (result: MotionResult) = let useVirtualSpace = _vimTextBuffer.UseVirtualSpace let shouldMaintainCaretColumn = Util.IsFlagSet result.MotionResultFlags MotionResultFlags.MaintainCaretColumn match shouldMaintainCaretColumn, result.CaretColumn with | true, CaretColumn.InLastLine columnNumber -> // Mappings should occur visually let visualLastLine = x.GetDirectionLastLineInVisualSnapshot result // First calculate the column in terms of spaces for the maintained caret. let caretColumnSpaces = let motionCaretColumnSpaces = if useVirtualSpace then x.GetSpacesToVirtualColumnNumber x.CaretLine columnNumber else x.GetSpacesToColumnNumber x.CaretLine columnNumber match x.MaintainCaretColumn with | MaintainCaretColumn.None -> motionCaretColumnSpaces | MaintainCaretColumn.Spaces maintainCaretColumnSpaces -> max maintainCaretColumnSpaces motionCaretColumnSpaces | MaintainCaretColumn.EndOfLine -> max 0 (visualLastLine.Length - 1) // Record the old setting. let oldMaintainCaretColumn = x.MaintainCaretColumn // The CaretColumn union is expressed in a position offset not a space offset // which can differ with tabs. Recalculate as appropriate. let caretColumn = x.GetAppropriateColumnForSpaces visualLastLine caretColumnSpaces |> (fun column -> column.VirtualColumnNumber) |> CaretColumn.InLastLine let result = { result with CaretColumn = caretColumn } // Complete the motion with the updated value then reset the maintain caret. Need // to do the save after the caret move since the move will clear out the saved value x.MoveCaretToMotionResultCore result x.MaintainCaretColumn <- match oldMaintainCaretColumn with | MaintainCaretColumn.EndOfLine -> MaintainCaretColumn.EndOfLine | _ -> if Util.IsFlagSet result.MotionResultFlags MotionResultFlags.EndOfLine then MaintainCaretColumn.EndOfLine else MaintainCaretColumn.Spaces caretColumnSpaces | _ -> // Not maintaining caret column so just do a normal movement x.MoveCaretToMotionResultCore result //If the motion wanted to maintain a specific column for the caret, we need to //save it. x.MaintainCaretColumn <- if Util.IsFlagSet result.MotionResultFlags MotionResultFlags.EndOfLine then MaintainCaretColumn.EndOfLine else match result.CaretColumn with | CaretColumn.ScreenColumn column -> MaintainCaretColumn.Spaces column | _ -> MaintainCaretColumn.None /// Many operations for moving a motion result need to be calculated in the /// visual snapshot. This method will return the DirectionLastLine value /// in that snapshot or the original value if no mapping is possible. member x.GetDirectionLastLineInVisualSnapshot (result: MotionResult): ITextSnapshotLine = let line = result.DirectionLastLine x.AdjustEditLineForVisualSnapshotLine line /// Move the caret to the position dictated by the given MotionResult value /// /// Note: This method mixes points from the edit and visual snapshot. Take care /// when changing this function to account for both. member x.MoveCaretToMotionResultCore (result: MotionResult) = let point = // All issues around caret column position should be calculated on the visual // snapshot let visualLine = x.GetDirectionLastLineInVisualSnapshot result if not result.IsForward then match result.MotionKind, result.CaretColumn with | MotionKind.LineWise, CaretColumn.InLastLine columnNumber -> // If we are moving linewise, but to a specific column, use // that column as the target of the motion let column = SnapshotColumn.GetForColumnNumberOrEnd(visualLine, columnNumber) column.StartPoint | _, _ -> result.Span.Start else match result.MotionKind with | MotionKind.CharacterWiseExclusive -> // Exclusive motions are straight forward. Move to the end of the SnapshotSpan // which was recorded. Exclusive doesn't include the last point in the span // but does move to it when going forward so End works here result.Span.End | MotionKind.CharacterWiseInclusive -> // Normal inclusive motion should move the caret to the last real point on the // SnapshotSpan. The exception is when we are in visual mode with an // exclusive selection. In that case we move as if it's an exclusive motion. // Couldn't find any documentation on this but it's indicated by several behavior // tests ('e', 'w' movements in particular). However, dollar is a special case. // In vim, it is allowed to move one further in visual mode regardless of // the selection kind. See issue #2258 and vim ':help $'. let adjustBackwards = if VisualKind.IsAnyVisual _vimTextBuffer.ModeKind then if _globalSettings.SelectionKind = SelectionKind.Exclusive then false elif result.MotionResultFlags.HasFlag MotionResultFlags.EndOfLine then false else true else true if adjustBackwards then SnapshotPointUtil.TryGetPreviousPointOnLine result.Span.End 1 |> OptionUtil.getOrDefault result.Span.End else result.Span.End | MotionKind.LineWise -> match result.CaretColumn with | CaretColumn.None -> visualLine.End | CaretColumn.InLastLine columnNumber -> let column = SnapshotColumn.GetForColumnNumberOrEnd(visualLine, columnNumber) column.StartPoint | CaretColumn.ScreenColumn columnNumber -> let column = SnapshotColumn.GetForColumnNumberOrEnd(visualLine, columnNumber) column.StartPoint | CaretColumn.AfterLastLine -> match SnapshotUtil.TryGetLine visualLine.Snapshot (visualLine.LineNumber + 1) with | None -> visualLine.End | Some visualLine -> visualLine.Start // The value 'point' may be in either the visual or edit snapshot at this point. Map to // ensure it's in the edit. let point = match BufferGraphUtil.MapPointDownToSnapshot _textView.BufferGraph point x.CurrentSnapshot PointTrackingMode.Negative PositionAffinity.Predecessor with | None -> point | Some point -> point let viewFlags = if result.OperationKind = OperationKind.LineWise && not (Util.IsFlagSet result.MotionResultFlags MotionResultFlags.ExclusiveLineWise) then // Line wise motions should not cause any collapsed regions to be expanded. Instead they // should leave the regions collapsed and just move the point into the region ViewFlags.All &&& (~~~ViewFlags.TextExpanded) else // Character wise motions should expand regions ViewFlags.All match _vimTextBuffer.UseVirtualSpace, result.CaretColumn with | true, CaretColumn.InLastLine column -> let columnNumber = SnapshotColumn(point).ColumnNumber let virtualSpaces = max 0 (column - columnNumber) point |> VirtualSnapshotPointUtil.OfPoint |> VirtualSnapshotPointUtil.AddOnSameLine virtualSpaces |> (fun point -> x.MoveCaretToVirtualPoint point viewFlags) | _ -> x.MoveCaretToPoint point viewFlags _editorOperations.ResetSelection() /// Move the caret to the proper indentation on a newly created line. The context line /// is provided to calculate an indentation off of member x.GetNewLineIndent (contextLine: ITextSnapshotLine) (newLine: ITextSnapshotLine) = match _vimHost.GetNewLineIndent _textView contextLine newLine _localSettings with | Some indent -> Some indent | None -> if _localSettings.AutoIndent then EditUtil.GetAutoIndent contextLine _localSettings.TabStop |> Some else None /// Get the standard ReplaceData for the given SnapshotPoint in the ITextBuffer member x.GetReplaceData point = let newLineText = x.GetNewLineText point { PreviousReplacement = _vimTextBuffer.Vim.VimData.LastSubstituteData |> Option.map (fun substituteData -> substituteData.Substitute) |> Option.defaultValue "" NewLine = newLineText Magic = _globalSettings.Magic Count = VimRegexReplaceCount.One } member x.IsLink (word: string) = word.StartsWith("http:", StringComparison.OrdinalIgnoreCase) || word.StartsWith("https:", StringComparison.OrdinalIgnoreCase) member x.IsVimLink (word: string) = word.IndexOf('|') <> -1 && word.IndexOf('|', word.IndexOf('|') + 1) <> -1 member x.GoToDefinition() = match x.WordUnderCursorOrEmpty with | "" -> Result.Failed(Resources.Common_GotoDefNoWordUnderCursor) | word when x.IsLink word -> x.OpenLinkUnderCaret() | word when x.IsVimLink word -> x.OpenVimLinkUnderCaret() | word -> let before = TextViewUtil.GetCaretVirtualPoint _textView if _vimHost.GoToDefinition() then _jumpList.Add before Result.Succeeded else Result.Failed(Resources.Common_GotoDefFailed word) member x.GoToLocalDeclaration() = let caretPoint = x.CaretVirtualPoint if _vimHost.GoToLocalDeclaration _textView x.WordUnderCursorOrEmpty then _jumpList.Add caretPoint else _vimHost.Beep() member x.GoToGlobalDeclaration () = let caretPoint = x.CaretVirtualPoint if _vimHost.GoToGlobalDeclaration _textView x.WordUnderCursorOrEmpty then _jumpList.Add caretPoint else _vimHost.Beep() member x.GoToFile () = x.GoToFile x.WordUnderCursorOrEmpty member x.GoToFile name = x.CheckDirty (fun () -> if not (_vimHost.LoadFileIntoExistingWindow name _textView) then _statusUtil.OnError (Resources.NormalMode_CantFindFile name)) /// Look for a word under the cursor and go to the specified file in a new window. member x.GoToFileInNewWindow () = x.GoToFileInNewWindow x.WordUnderCursorOrEmpty /// No need to check for dirty since we are opening a new window member x.GoToFileInNewWindow name = match x.LoadFileIntoNewWindow name (Some 0) None with | Result.Succeeded -> () | Result.Failed message -> _statusUtil.OnError message member x.GoToNextTab path count = let tabCount = _vimHost.TabCount let mutable tabIndex = _vimHost.GetTabIndex _textView if tabCount >= 0 && tabIndex >= 0 && tabIndex < tabCount then let count = count % tabCount match path with | SearchPath.Forward -> tabIndex <- tabIndex + count tabIndex <- tabIndex % tabCount | SearchPath.Backward -> tabIndex <- tabIndex - count if tabIndex < 0 then tabIndex <- tabIndex + tabCount _vimHost.GoToTab tabIndex member x.GoToTab index = // Normalize out the specified tabIndex to a 0 based value. Vim uses some odd // logic here but the host represents the tab as a 0 based list of tabs let mutable tabIndex = index let tabCount = _vimHost.TabCount if tabCount > 0 then if tabIndex < 0 then tabIndex <- tabCount - 1 elif tabIndex > 0 then tabIndex <- tabIndex - 1 if tabIndex >= 0 && tabIndex < tabCount then _vimHost.GoToTab tabIndex /// Using the specified base folder, go to the tag specified by ident member x.GoToTagInNewWindow baseFolder ident = let folder = baseFolder // Function to read lines from file without throwing exceptions let readAllLines file = try System.IO.File.ReadAllLines(file) with | _ -> Array.empty<string> // Look up the ident in the tags file, preferring an exact match, then // the shortest case-insensitive prefix match. let target = match ident with | "" -> None | _ -> let tags = System.IO.Path.Combine(folder, "tags") readAllLines tags |> Seq.map (fun line -> match line.Split([| '\t' |]) with | fields when fields.Length = 3 -> Some (fields.[0], fields.[1], fields.[2]) | _ -> None) |> Seq.choose id |> Seq.filter (fun (tag, _, _) -> tag.StartsWith(ident, System.StringComparison.OrdinalIgnoreCase)) |> Seq.sortBy (fun (tag, _, _) -> tag.Length) |> Seq.sortByDescending (fun (tag, _, _) -> tag = ident) |> Seq.tryHead // Try to navigate to the tag. match target with | Some (tag, file, pattern) -> // Load the target file into a new window and navigate to the tag. // If the tag was not found in the file, go to the first line. let targetFile = System.IO.Path.Combine(folder, file) let pattern = pattern.Substring(1) let lineNumber, columnNumber = readAllLines targetFile |> Seq.mapi (fun lineNumber line -> lineNumber, line) |> Seq.map (fun (lineNumber, line) -> lineNumber, line.IndexOf(pattern)) |> Seq.filter (fun (_, columnNumber) -> columnNumber <> -1) |> Seq.map (fun (lineNumber, columnNumber) -> Some lineNumber, Some columnNumber) diff --git a/Test/VimCoreTest/CommonOperationsTest.cs b/Test/VimCoreTest/CommonOperationsTest.cs index 960dd37..76478c4 100644 --- a/Test/VimCoreTest/CommonOperationsTest.cs +++ b/Test/VimCoreTest/CommonOperationsTest.cs @@ -1,671 +1,671 @@ using System; using System.Collections.Generic; using System.Linq; using Vim.EditorHost; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Outlining; using Moq; using Vim.Extensions; using Vim.UnitTest.Mock; using Xunit; using Microsoft.FSharp.Core; using System.Threading; namespace Vim.UnitTest { public class CommonOperationsTest : VimTestBase { private TestableSynchronizationContext _context; private ITextView _textView; private ITextBuffer _textBuffer; private IFoldManager _foldManager; private IRegisterMap _registerMap; private MockRepository _factory; private Mock<IVimHost> _vimHost; private Mock<IJumpList> _jumpList; private Mock<IVimLocalSettings> _localSettings; private Mock<IOutliningManager> _outlining; private Mock<IStatusUtil> _statusUtil; private Mock<IVimTextBuffer> _vimTextBuffer; private IUndoRedoOperations _undoRedoOperations; private ISearchService _searchService; private IVimData _vimData; private ICommonOperations _operations; private CommonOperations _operationsRaw; protected void Create(params string[] lines) { _context = new TestableSynchronizationContext(); _textView = CreateTextView(lines); _textView.Caret.MoveTo(new SnapshotPoint(_textView.TextSnapshot, 0)); _textBuffer = _textView.TextBuffer; _foldManager = FoldManagerFactory.GetFoldManager(_textView); _factory = new MockRepository(MockBehavior.Strict); // Create the Vim instance with our Mock'd services _registerMap = Vim.RegisterMap; _vimHost = _factory.Create<IVimHost>(); _vimHost.Setup(x => x.DoActionWhenTextViewReady(It.IsAny<FSharpFunc<Unit, Unit>>(), It.IsAny<ITextView>())) .Callback((FSharpFunc<Unit, Unit> action, ITextView textView) => action.Invoke(null)); var globalSettings = Vim.GlobalSettings; globalSettings.Magic = true; globalSettings.SmartCase = false; globalSettings.IgnoreCase = true; globalSettings.VirtualEdit = "onemore"; globalSettings.Selection = "inclusive"; globalSettings.WrapScan = true; _vimData = new VimData(globalSettings); _searchService = new SearchService(TextSearchService, globalSettings); var vim = MockObjectFactory.CreateVim( registerMap: _registerMap, host: _vimHost.Object, globalSettings: globalSettings, searchService: _searchService, factory: _factory); // Create the IVimTextBuffer instance with our Mock'd services _localSettings = MockObjectFactory.CreateLocalSettings(globalSettings, _factory); _localSettings.SetupGet(x => x.AutoIndent).Returns(false); _localSettings.SetupGet(x => x.GlobalSettings).Returns(globalSettings); _localSettings.SetupGet(x => x.ExpandTab).Returns(true); _localSettings.SetupGet(x => x.TabStop).Returns(4); _localSettings.SetupGet(x => x.ShiftWidth).Returns(2); _localSettings.SetupGet(x => x.IsKeyword).Returns("@,_,0-9"); _localSettings.SetupGet(x => x.IsKeywordCharSet).Returns(VimCharSet.TryParse("@,_,0-9").Value); _statusUtil = _factory.Create<IStatusUtil>(); _undoRedoOperations = VimUtil.CreateUndoRedoOperations(_statusUtil.Object); _vimTextBuffer = MockObjectFactory.CreateVimTextBuffer( _textBuffer, localSettings: _localSettings.Object, vim: vim.Object, undoRedoOperations: _undoRedoOperations, factory: _factory); _vimTextBuffer.SetupGet(x => x.UseVirtualSpace).Returns(false); _vimTextBuffer.SetupGet(x => x.InOneTimeCommand).Returns(FSharpOption<ModeKind>.None); // Create the VimBufferData instance with our Mock'd services _jumpList = _factory.Create<IJumpList>(); var vimBufferData = CreateVimBufferData( _vimTextBuffer.Object, _textView, statusUtil: _statusUtil.Object, jumpList: _jumpList.Object); _outlining = _factory.Create<IOutliningManager>(); _outlining .Setup(x => x.ExpandAll(It.IsAny<SnapshotSpan>(), It.IsAny<Predicate<ICollapsed>>())) .Returns<IEnumerable<ICollapsible>>(null); var commonOperationsFactory = _factory.Create<ICommonOperationsFactory>(); var bulkOperations = CompositionContainer.GetExportedValue<IBulkOperations>(); _operationsRaw = new CommonOperations( commonOperationsFactory.Object, vimBufferData, EditorOperationsFactoryService.GetEditorOperations(_textView), FSharpOption.Create(_outlining.Object), MouseDevice, bulkOperations); _operations = _operationsRaw; commonOperationsFactory.Setup(x => x.GetCommonOperations(vimBufferData)).Returns(_operations); } private static string CreateLinesWithLineBreak(params string[] lines) { return lines.Aggregate((x, y) => x + Environment.NewLine + y) + Environment.NewLine; } public sealed class MiscTest : CommonOperationsTest { /// <summary> /// Standard case of deleting several lines in the buffer /// </summary> [WpfFact] public void DeleteLines_Multiple() { Create("cat", "dog", "bear"); _operations.DeleteLines(_textBuffer.GetLine(0), 2, VimUtil.MissingRegisterName); Assert.Equal(CreateLinesWithLineBreak("cat", "dog"), UnnamedRegister.StringValue); Assert.Equal("bear", _textView.GetLine(0).GetText()); Assert.Equal(OperationKind.LineWise, UnnamedRegister.OperationKind); } /// <summary> /// Verify the deleting of lines where the count causes the deletion to cross /// over a fold /// </summary> [WpfFact] public void DeleteLines_OverFold() { Create("cat", "dog", "bear", "fish", "tree"); _foldManager.CreateFold(_textView.GetLineRange(1, 2)); - _operations.DeleteLines(_textBuffer.GetLine(0), 3, VimUtil.MissingRegisterName); + _operations.DeleteLines(_textBuffer.GetLine(0), 4, VimUtil.MissingRegisterName); Assert.Equal(CreateLinesWithLineBreak("cat", "dog", "bear", "fish"), UnnamedRegister.StringValue); Assert.Equal("tree", _textView.GetLine(0).GetText()); Assert.Equal(OperationKind.LineWise, UnnamedRegister.OperationKind); } /// <summary> /// Verify the deleting of lines where the count causes the deletion to cross /// over a fold which begins the deletion span /// </summary> [WpfFact] public void DeleteLines_StartOfFold() { Create("cat", "dog", "bear", "fish", "tree"); _foldManager.CreateFold(_textView.GetLineRange(0, 1)); - _operations.DeleteLines(_textBuffer.GetLine(0), 2, VimUtil.MissingRegisterName); + _operations.DeleteLines(_textBuffer.GetLine(0), 3, VimUtil.MissingRegisterName); Assert.Equal(CreateLinesWithLineBreak("cat", "dog", "bear"), UnnamedRegister.StringValue); Assert.Equal("fish", _textView.GetLine(0).GetText()); Assert.Equal(OperationKind.LineWise, UnnamedRegister.OperationKind); } [WpfFact] public void DeleteLines_Simple() { Create("foo", "bar", "baz", "jaz"); _operations.DeleteLines(_textBuffer.GetLine(0), 1, VimUtil.MissingRegisterName); Assert.Equal("bar", _textView.GetLine(0).GetText()); Assert.Equal("foo" + Environment.NewLine, UnnamedRegister.StringValue); Assert.Equal(0, _textView.GetCaretPoint().Position); } [WpfFact] public void DeleteLines_WithCount() { Create("foo", "bar", "baz", "jaz"); _operations.DeleteLines(_textBuffer.GetLine(0), 2, VimUtil.MissingRegisterName); Assert.Equal("baz", _textView.GetLine(0).GetText()); Assert.Equal("foo" + Environment.NewLine + "bar" + Environment.NewLine, UnnamedRegister.StringValue); Assert.Equal(0, _textView.GetCaretPoint().Position); } /// <summary> /// Delete the last line and make sure it actually deletes a line from the buffer /// </summary> [WpfFact] public void DeleteLines_LastLine() { Create("foo", "bar"); _operations.DeleteLines(_textBuffer.GetLine(1), 1, VimUtil.MissingRegisterName); Assert.Equal("bar" + Environment.NewLine, UnnamedRegister.StringValue); Assert.Equal(1, _textView.TextSnapshot.LineCount); Assert.Equal("foo", _textView.GetLine(0).GetText()); } /// <summary> /// Ensure that a join of 2 lines which don't have any blanks will produce lines which /// are separated by a single space /// </summary> [WpfFact] public void Join_RemoveSpaces_NoBlanks() { Create("foo", "bar"); _operations.Join(_textView.GetLineRange(0, 1), JoinKind.RemoveEmptySpaces); Assert.Equal("foo bar", _textView.TextSnapshot.GetLineFromLineNumber(0).GetText()); Assert.Equal(1, _textView.TextSnapshot.LineCount); } /// <summary> /// Ensure that we properly remove the leading spaces at the start of the next line if /// we are removing spaces /// </summary> [WpfFact] public void Join_RemoveSpaces_BlanksStartOfSecondLine() { Create("foo", " bar"); _operations.Join(_textView.GetLineRange(0, 1), JoinKind.RemoveEmptySpaces); Assert.Equal("foo bar", _textView.TextSnapshot.GetLineFromLineNumber(0).GetText()); Assert.Equal(1, _textView.TextSnapshot.LineCount); } /// <summary> /// Don't touch the spaces when we join without editing them /// </summary> [WpfFact] public void Join_KeepSpaces_BlanksStartOfSecondLine() { Create("foo", " bar"); _operations.Join(_textView.GetLineRange(0, 1), JoinKind.KeepEmptySpaces); Assert.Equal("foo bar", _textView.TextSnapshot.GetLineFromLineNumber(0).GetText()); Assert.Equal(1, _textView.TextSnapshot.LineCount); } /// <summary> /// Do a join of 3 lines /// </summary> [WpfFact] public void Join_RemoveSpaces_ThreeLines() { Create("foo", "bar", "baz"); _operations.Join(_textView.GetLineRange(0, 2), JoinKind.RemoveEmptySpaces); Assert.Equal("foo bar baz", _textView.TextSnapshot.GetLineFromLineNumber(0).GetText()); Assert.Equal(1, _textView.TextSnapshot.LineCount); } /// <summary> /// Ensure we can properly join an empty line /// </summary> [WpfFact] public void Join_RemoveSpaces_EmptyLine() { Create("cat", "", "dog", "tree", "rabbit"); _operations.Join(_textView.GetLineRange(0, 1), JoinKind.RemoveEmptySpaces); Assert.Equal("cat ", _textView.GetLine(0).GetText()); Assert.Equal("dog", _textView.GetLine(1).GetText()); } /// <summary> /// No tabs is just a column offset /// </summary> [WpfFact] public void GetSpacesToColumn_NoTabs() { Create("hello world"); Assert.Equal(2, _operationsRaw.GetSpacesToColumnNumber(_textBuffer.GetLine(0), 2)); } /// <summary> /// Tabs count as tabstop spaces /// </summary> [WpfFact] public void GetSpacesToColumn_Tabs() { Create("\thello world"); _localSettings.SetupGet(x => x.TabStop).Returns(4); Assert.Equal(5, _operationsRaw.GetSpacesToColumnNumber(_textBuffer.GetLine(0), 2)); } /// <summary> /// Wide characters count double /// </summary> [WpfFact] public void GetSpacesToColumn_WideChars() { Create("\u3042\u3044\u3046\u3048\u304A"); Assert.Equal(10, _operationsRaw.GetSpacesToColumnNumber(_textBuffer.GetLine(0), 5)); } /// <summary> /// Non spacing characters are not taken into account /// </summary> [WpfFact] public void GetSpacesToColumn_NonSpacingChars() { // h̸ello̊​w̵orld Create("h\u0338ello\u030A\u200bw\u0335orld"); Assert.Equal(10, _operationsRaw.GetSpacesToColumnNumber(_textBuffer.GetLine(0), 14)); } /// <summary> /// Without any tabs this should be a straight offset /// </summary> [WpfFact] public void GetPointForSpaces_NoTabs() { Create("hello world"); var column = _operationsRaw.GetColumnForSpacesOrEnd(_textBuffer.GetLine(0), 2); Assert.Equal(_textBuffer.GetPoint(2), column.StartPoint); } /// <summary> /// Count the tabs as a 'tabstop' value when calculating the Point /// </summary> [WpfFact] public void GetPointForSpaces_Tabs() { Create("\thello world"); _localSettings.SetupGet(x => x.TabStop).Returns(4); var column = _operationsRaw.GetColumnForSpacesOrEnd(_textBuffer.GetLine(0), 5); Assert.Equal(_textBuffer.GetPoint(2), column.StartPoint); } /// <summary> /// Verify that we properly return the new line text for the first line /// </summary> [WpfFact] public void GetNewLineText_FirstLine() { Create("cat", "dog"); Assert.Equal(Environment.NewLine, _operations.GetNewLineText(_textBuffer.GetPoint(0))); } /// <summary> /// Verify that we properly return the new line text for the first line when using a non /// default new line ending /// </summary> [WpfFact] public void GetNewLineText_FirstLine_LineFeed() { Create("cat", "dog"); _textBuffer.Replace(new Span(0, 0), "cat\ndog"); Assert.Equal("\n", _operations.GetNewLineText(_textBuffer.GetPoint(0))); } /// <summary> /// Verify that we properly return the new line text for middle lines /// </summary> [WpfFact] public void GetNewLineText_MiddleLine() { Create("cat", "dog", "bear"); Assert.Equal(Environment.NewLine, _operations.GetNewLineText(_textBuffer.GetLine(1).Start)); } /// <summary> /// Verify that we properly return the new line text for middle lines when using a non /// default new line ending /// </summary> [WpfFact] public void GetNewLineText_MiddleLine_LineFeed() { Create(""); _textBuffer.Replace(new Span(0, 0), "cat\ndog\nbear"); Assert.Equal("\n", _operations.GetNewLineText(_textBuffer.GetLine(1).Start)); } /// <summary> /// Verify that we properly return the new line text for end lines /// </summary> [WpfFact] public void GetNewLineText_EndLine() { Create("cat", "dog", "bear"); Assert.Equal(Environment.NewLine, _operations.GetNewLineText(_textBuffer.GetLine(2).Start)); } /// <summary> /// Verify that we properly return the new line text for middle lines when using a non /// default new line ending /// </summary> [WpfFact] public void GetNewLineText_EndLine_LineFeed() { Create(""); _textBuffer.Replace(new Span(0, 0), "cat\ndog\nbear"); Assert.Equal("\n", _operations.GetNewLineText(_textBuffer.GetLine(2).Start)); } [WpfFact] public void GoToDefinition1() { Create("foo"); _jumpList.Setup(x => x.Add(_textView.GetCaretVirtualPoint())).Verifiable(); _vimHost.Setup(x => x.GoToDefinition()).Returns(true); var res = _operations.GoToDefinition(); Assert.True(res.IsSucceeded); _jumpList.Verify(); } [WpfFact] public void GoToDefinition2() { Create("foo"); _vimHost.Setup(x => x.GoToDefinition()).Returns(false); var res = _operations.GoToDefinition(); Assert.True(res.IsFailed); Assert.Contains("foo", ((Result.Failed)res).Error); } /// <summary> /// Make sure we don't crash when nothing is under the cursor /// </summary> [WpfFact] public void GoToDefinition3() { Create(" foo"); _vimHost.Setup(x => x.GoToDefinition()).Returns(false); var res = _operations.GoToDefinition(); Assert.True(res.IsFailed); } [WpfFact] public void GoToDefinition4() { Create(" foo"); _vimHost.Setup(x => x.GoToDefinition()).Returns(false); var res = _operations.GoToDefinition(); Assert.True(res.IsFailed); Assert.Equal(Resources.Common_GotoDefNoWordUnderCursor, res.AsFailed().Error); } [WpfFact] public void GoToDefinition5() { Create("foo bar baz"); _vimHost.Setup(x => x.GoToDefinition()).Returns(false); var res = _operations.GoToDefinition(); Assert.True(res.IsFailed); Assert.Equal(Resources.Common_GotoDefFailed("foo"), res.AsFailed().Error); } /// <summary> /// Simple insertion of a single item into the ITextBuffer /// </summary> [WpfFact] public void Put_Single() { Create("dog", "cat"); _operations.Put(_textView.GetLine(0).Start.Add(1), StringData.NewSimple("fish"), OperationKind.CharacterWise); Assert.Equal("dfishog", _textView.GetLine(0).GetText()); } /// <summary> /// Put a block StringData value into the ITextBuffer over existing text /// </summary> [WpfFact] public void Put_BlockOverExisting() { Create("dog", "cat"); _operations.Put(_textView.GetLine(0).Start, VimUtil.CreateStringDataBlock("a", "b"), OperationKind.CharacterWise); Assert.Equal("adog", _textView.GetLine(0).GetText()); Assert.Equal("bcat", _textView.GetLine(1).GetText()); } /// <summary> /// Put a block StringData value into the ITextBuffer where the length of the values /// exceeds the number of lines in the ITextBuffer. This will force the insert to create /// new lines to account for it /// </summary> [WpfFact] public void Put_BlockLongerThanBuffer() { Create("dog"); _operations.Put(_textView.GetLine(0).Start.Add(1), VimUtil.CreateStringDataBlock("a", "b"), OperationKind.CharacterWise); Assert.Equal("daog", _textView.GetLine(0).GetText()); Assert.Equal(" b", _textView.GetLine(1).GetText()); } /// <summary> /// A linewise insertion for Block should just insert each value onto a new line /// </summary> [WpfFact] public void Put_BlockLineWise() { Create("dog", "cat"); _operations.Put(_textView.GetLine(1).Start, VimUtil.CreateStringDataBlock("a", "b"), OperationKind.LineWise); Assert.Equal("dog", _textView.GetLine(0).GetText()); Assert.Equal("a", _textView.GetLine(1).GetText()); Assert.Equal("b", _textView.GetLine(2).GetText()); Assert.Equal("cat", _textView.GetLine(3).GetText()); } /// <summary> /// Put a single StringData instance linewise into the ITextBuffer. /// </summary> [WpfFact] public void Put_LineWiseSingleWord() { Create("cat"); _operations.Put(_textView.GetLine(0).Start, StringData.NewSimple("fish\n"), OperationKind.LineWise); Assert.Equal("fish", _textView.GetLine(0).GetText()); Assert.Equal("cat", _textView.GetLine(1).GetText()); } /// <summary> /// Do a put at the end of the ITextBuffer which is of a single StringData and is characterwise /// </summary> [WpfFact] public void Put_EndOfBufferSingleCharacterwise() { Create("cat"); _operations.Put(_textView.GetEndPoint(), StringData.NewSimple("dog"), OperationKind.CharacterWise); Assert.Equal("catdog", _textView.GetLine(0).GetText()); } /// <summary> /// Do a put at the end of the ITextBuffer linewise. This is a corner case because the code has /// to move the final line break from the end of the StringData to the front. Ensure that we don't /// keep the final \n in the inserted string because that will mess up the line count in the /// ITextBuffer /// </summary> [WpfFact] public void Put_EndOfBufferLinewise() { Create("cat"); Assert.Equal(1, _textView.TextSnapshot.LineCount); _operations.Put(_textView.GetEndPoint(), StringData.NewSimple("dog\n"), OperationKind.LineWise); Assert.Equal("cat", _textView.GetLine(0).GetText()); Assert.Equal("dog", _textView.GetLine(1).GetText()); Assert.Equal(2, _textView.TextSnapshot.LineCount); } /// <summary> /// Do a put at the end of the ITextBuffer linewise. Same as previous /// test but the buffer contains a trailing line break /// </summary> [WpfFact] public void Put_EndOfBufferLinewiseWithTrailingLineBreak() { Create("cat", ""); Assert.Equal(2, _textView.TextSnapshot.LineCount); _operations.Put(_textView.GetEndPoint(), StringData.NewSimple("dog\n"), OperationKind.LineWise); Assert.Equal("cat", _textView.GetLine(0).GetText()); Assert.Equal("dog", _textView.GetLine(1).GetText()); Assert.Equal(3, _textView.TextSnapshot.LineCount); } /// <summary> /// Put into empty buffer should create a buffer with the contents being put /// </summary> [WpfFact] public void Put_IntoEmptyBuffer() { Create(""); _operations.Put(_textView.GetLine(0).Start, StringData.NewSimple("fish\n"), OperationKind.LineWise); Assert.Equal("fish", _textView.GetLine(0).GetText()); } /// <summary> /// Only shift whitespace /// </summary> [WpfFact] public void ShiftLineRangeLeft1() { Create("foo"); _operations.ShiftLineRangeLeft(_textBuffer.GetLineRange(0), 1); Assert.Equal("foo", _textBuffer.CurrentSnapshot.GetLineFromLineNumber(0).GetText()); } /// <summary> /// Don't puke on an empty line /// </summary> [WpfFact] public void ShiftLineRangeLeft2() { Create(""); _operations.ShiftLineRangeLeft(_textBuffer.GetLineRange(0), 1); Assert.Equal("", _textBuffer.CurrentSnapshot.GetLineFromLineNumber(0).GetText()); } [WpfFact] public void ShiftLineRangeLeft3() { Create(" foo", " bar"); _operations.ShiftLineRangeLeft(_textBuffer.GetLineRange(0, 1), 1); Assert.Equal("foo", _textBuffer.CurrentSnapshot.GetLineFromLineNumber(0).GetText()); Assert.Equal("bar", _textBuffer.CurrentSnapshot.GetLineFromLineNumber(1).GetText()); } [WpfFact] public void ShiftLineRangeLeft4() { Create(" foo"); _operations.ShiftLineRangeLeft(_textBuffer.GetLineRange(0), 1); Assert.Equal(" foo", _textBuffer.CurrentSnapshot.GetLineFromLineNumber(0).GetText()); } [WpfFact] public void ShiftLineRangeLeft5() { Create(" a", " b", "c"); _operations.ShiftLineRangeLeft(_textBuffer.GetLineRange(0), 1); Assert.Equal("a", _textBuffer.GetLine(0).GetText()); Assert.Equal(" b", _textBuffer.GetLine(1).GetText()); } [WpfFact] public void ShiftLineRangeLeft6() { Create(" foo"); _operations.ShiftLineRangeLeft(_textView.GetLineRange(0), 1); Assert.Equal(" foo", _textBuffer.GetLineRange(0).GetText()); } [WpfFact] public void ShiftLineRangeLeft7() { Create(" foo"); _operations.ShiftLineRangeLeft(_textView.GetLineRange(0), 400); Assert.Equal("foo", _textBuffer.GetLineRange(0).GetText()); } [WpfFact] public void ShiftLineRangeLeft8() { Create(" foo", " bar"); _operations.ShiftLineRangeLeft(2); Assert.Equal(" foo", _textBuffer.GetLineRange(0).GetText()); Assert.Equal(" bar", _textBuffer.GetLineRange(1).GetText()); } [WpfFact] public void ShiftLineRangeLeft9() { Create(" foo", " bar"); _textView.MoveCaretTo(_textBuffer.GetLineRange(1).Start.Position); _operations.ShiftLineRangeLeft(1); Assert.Equal(" foo", _textBuffer.GetLineRange(0).GetText()); Assert.Equal(" bar", _textBuffer.GetLineRange(1).GetText()); } [WpfFact] public void ShiftLineRangeLeft10() { Create(" foo", "", " bar"); _operations.ShiftLineRangeLeft(3); Assert.Equal("foo", _textBuffer.GetLineRange(0).GetText()); Assert.Equal("", _textBuffer.GetLineRange(1).GetText()); Assert.Equal(" bar", _textBuffer.GetLineRange(2).GetText()); } [WpfFact] public void ShiftLineRangeLeft11() { Create(" foo", " ", " bar"); _operations.ShiftLineRangeLeft(3); Assert.Equal("foo", _textBuffer.GetLineRange(0).GetText()); Assert.Equal(" ", _textBuffer.GetLineRange(1).GetText()); Assert.Equal(" bar", _textBuffer.GetLineRange(2).GetText()); } [WpfFact] public void ShiftLineRangeLeft_TabStartUsingSpaces() { Create("\tcat"); _localSettings.SetupGet(x => x.ExpandTab).Returns(true); _operations.ShiftLineRangeLeft(1); Assert.Equal(" cat", _textView.GetLine(0).GetText()); }
VsVim/VsVim
a756538a1577f87ed68881f957d21f9c797cf043
API clean up
diff --git a/Src/VimCore/CoreInterfaces.fs b/Src/VimCore/CoreInterfaces.fs index bb6d9ae..70fdfbc 100644 --- a/Src/VimCore/CoreInterfaces.fs +++ b/Src/VimCore/CoreInterfaces.fs @@ -3667,1027 +3667,1032 @@ type InsertCommand = | TextChange.Combination (left, right) -> let leftCommand = InsertCommand.OfTextChange left let rightCommand = InsertCommand.OfTextChange right InsertCommand.Combined (leftCommand, rightCommand) /// Convert this InsertCommand to a TextChange object member x.TextChange editorOptions textBuffer = match x with | InsertCommand.Back -> Some (TextChange.DeleteLeft 1) | InsertCommand.BlockInsert _ -> None | InsertCommand.Combined (left, right) -> match left.TextChange editorOptions textBuffer, right.TextChange editorOptions textBuffer with | Some l, Some r -> TextChange.Combination (l, r) |> Some | _ -> None | InsertCommand.CompleteMode _ -> None | InsertCommand.Delete -> Some (TextChange.DeleteRight 1) | InsertCommand.DeleteLeft count -> Some (TextChange.DeleteLeft count) | InsertCommand.DeleteRight count -> Some (TextChange.DeleteRight count) | InsertCommand.DeleteAllIndent -> None | InsertCommand.DeleteWordBeforeCursor -> None | InsertCommand.Insert text -> Some (TextChange.Insert text) | InsertCommand.InsertLiteral text -> Some (TextChange.Insert text) | InsertCommand.InsertCharacterAboveCaret -> None | InsertCommand.InsertCharacterBelowCaret -> None | InsertCommand.InsertNewLine -> Some (TextChange.Insert (EditUtil.NewLine editorOptions textBuffer)) | InsertCommand.InsertPreviouslyInsertedText _ -> None | InsertCommand.InsertTab -> Some (TextChange.Insert "\t") | InsertCommand.MoveCaret _ -> None | InsertCommand.MoveCaretWithArrow _ -> None | InsertCommand.MoveCaretByWord _ -> None | InsertCommand.MoveCaretToEndOfLine -> None | InsertCommand.Replace c -> Some (TextChange.Combination ((TextChange.DeleteRight 1), (TextChange.Insert (c.ToString())))) | InsertCommand.ReplaceCharacterAboveCaret -> None | InsertCommand.ReplaceCharacterBelowCaret -> None | InsertCommand.Overwrite s -> Some (TextChange.Replace s) | InsertCommand.ShiftLineLeft -> None | InsertCommand.ShiftLineRight -> None | InsertCommand.UndoReplace -> None | InsertCommand.DeleteLineBeforeCursor -> None | InsertCommand.Paste -> None /// Commands which can be executed by the user [<RequireQualifiedAccess>] [<StructuralEquality>] [<NoComparison>] type Command = /// A Normal Mode Command | NormalCommand of NormalCommand: NormalCommand * CommandData: CommandData /// A Visual Mode Command | VisualCommand of VisualCommand: VisualCommand * CommandData: CommandData * VisualSpan: VisualSpan /// An Insert / Replace Mode Command | InsertCommand of InsertCommand: InsertCommand /// This is the result of attemping to bind a series of KeyInput values into a Motion /// Command, etc ... [<RequireQualifiedAccess>] type BindResult<'T> = /// Successfully bound to a value | Complete of Result: 'T /// More input is needed to complete the binding operation | NeedMoreInput of BindData: BindData<'T> /// There was an error completing the binding operation | Error /// Motion was cancelled via user input | Cancelled with /// Used to compose to BindResult<'T> functions together by forwarding from /// one to the other once the value is completed member x.Map (mapFunc: 'T -> BindResult<'U>): BindResult<'U> = match x with | Complete value -> mapFunc value | NeedMoreInput (bindData: BindData<'T>) -> NeedMoreInput (bindData.Map mapFunc) | Error -> Error | Cancelled -> Cancelled /// Used to convert a BindResult<'T>.Completed to BindResult<'U>.Completed through a conversion /// function member x.Convert (convertFunc: 'T -> 'U): BindResult<'U> = x.Map (fun value -> convertFunc value |> BindResult.Complete) and BindData<'T> = { /// The optional KeyRemapMode which should be used when binding /// the next KeyInput in the sequence KeyRemapMode: KeyRemapMode /// Function to call to get the BindResult for this data BindFunction: KeyInput -> BindResult<'T> } with member x.CreateBindResult() = BindResult.NeedMoreInput x /// Used for BindData where there can only be a complete result for a given /// KeyInput. static member CreateForKeyInput keyRemapMode valueFunc = let bindFunc keyInput = let value = valueFunc keyInput BindResult<_>.Complete value { KeyRemapMode = keyRemapMode; BindFunction = bindFunc } /// Used for BindData where there can only be a complete result for a given /// char static member CreateForChar keyRemapMode valueFunc = BindData<_>.CreateForKeyInput keyRemapMode (fun keyInput -> valueFunc keyInput.Char) /// Very similar to the Convert function. This will instead map a BindData<'T>.Completed /// to a BindData<'U> of any form member x.Map<'U> (mapFunc: 'T -> BindResult<'U>): BindData<'U> = let originalBindFunc = x.BindFunction let bindFunc keyInput = match originalBindFunc keyInput with | BindResult.Cancelled -> BindResult.Cancelled | BindResult.Complete value -> mapFunc value | BindResult.Error -> BindResult.Error | BindResult.NeedMoreInput bindData -> BindResult.NeedMoreInput (bindData.Map mapFunc) { KeyRemapMode = x.KeyRemapMode; BindFunction = bindFunc } /// Often types bindings need to compose together because we need an inner binding /// to succeed so we can create a projected value. This function will allow us /// to translate a BindResult<'T>.Completed -> BindResult<'U>.Completed member x.Convert (convertFunc: 'T -> 'U): BindData<'U> = x.Map (fun value -> convertFunc value |> BindResult.Complete) /// Several types of BindData<'T> need to take an action when a binding begins against /// themselves. This action needs to occur before the first KeyInput value is processed /// and hence they need a jump start. The most notable is IncrementalSearch which /// needs to enter 'Search' mode before processing KeyInput values so the cursor can /// be updated [<RequireQualifiedAccess>] type BindDataStorage<'T> = /// Simple BindData<'T> which doesn't require activation | Simple of BindData: BindData<'T> /// Complex BindData<'T> which does require activation | Complex of CreateBindDataFunc: (unit -> BindData<'T>) with /// Creates the BindData member x.CreateBindData () = match x with | Simple bindData -> bindData | Complex func -> func() /// Convert from a BindDataStorage<'T> -> BindDataStorage<'U>. The 'mapFunc' value /// will run on the final 'T' data if it eventually is completed member x.Convert mapFunc = match x with | Simple bindData -> Simple (bindData.Convert mapFunc) | Complex func -> Complex (fun () -> func().Convert mapFunc) /// This is the result of attemping to bind a series of KeyInputData values /// into a Motion Command, etc ... [<RequireQualifiedAccess>] type MappedBindResult<'T> = /// Successfully bound to a value | Complete of Result: 'T /// More input is needed to complete the binding operation | NeedMoreInput of MappedBindData: MappedBindData<'T> /// There was an error completing the binding operation | Error /// Motion was cancelled via user input | Cancelled with /// Used to compose to MappedBindResult<'T> functions together by /// forwarding from one to the other once the value is completed member x.Map (mapFunc: 'T -> MappedBindResult<'U>): MappedBindResult<'U> = match x with | Complete value -> mapFunc value | NeedMoreInput (bindData: MappedBindData<'T>) -> NeedMoreInput (bindData.Map mapFunc) | Error -> Error | Cancelled -> Cancelled /// Used to convert a MappedBindResult<'T>.Completed to /// MappedBindResult<'U>.Completed through a conversion function member x.Convert (convertFunc: 'T -> 'U): MappedBindResult<'U> = x.Map (fun value -> convertFunc value |> MappedBindResult.Complete) /// Convert this MappedBindResult<'T> to a BindResult<'T> member x.ConvertToBindResult (): BindResult<'T> = match x with | MappedBindResult.Complete result -> BindResult.Complete result | MappedBindResult.NeedMoreInput mappedBindData -> BindResult.NeedMoreInput (mappedBindData.ConvertToBindData()) | MappedBindResult.Error -> BindResult.Error | MappedBindResult.Cancelled -> BindResult.Cancelled and MappedBindData<'T> = { /// The optional KeyRemapMode which should be used when binding the next /// KeyInput in the sequence KeyRemapMode: KeyRemapMode /// Function to call to get the MappedBindResult for this data MappedBindFunction: KeyInputData -> MappedBindResult<'T> } with member x.CreateBindResult() = MappedBindResult.NeedMoreInput x /// Very similar to the Convert function. This will instead map a /// MappedBindData<'T>.Completed to a MappedBindData<'U> of any form member x.Map<'U> (mapFunc: 'T -> MappedBindResult<'U>): MappedBindData<'U> = let originalBindFunc = x.MappedBindFunction let bindFunc keyInputData = match originalBindFunc keyInputData with | MappedBindResult.Complete value -> mapFunc value | MappedBindResult.NeedMoreInput mappedBindData -> MappedBindResult.NeedMoreInput (mappedBindData.Map mapFunc) | MappedBindResult.Error -> MappedBindResult.Error | MappedBindResult.Cancelled -> MappedBindResult.Cancelled { KeyRemapMode = x.KeyRemapMode; MappedBindFunction = bindFunc } /// Often types bindings need to compose together because we need an inner /// binding to succeed so we can create a projected value. This function /// will allow us to translate a MappedBindResult<'T>.Completed -> /// MappedBindResult<'U>.Completed member x.Convert (convertFunc: 'T -> 'U): MappedBindData<'U> = x.Map (fun value -> convertFunc value |> MappedBindResult.Complete) /// Convert this MappedBindData<'T> to a BindData<'T> (note that as a /// result of the conversion all key inputs will all appear to be unmapped) member x.ConvertToBindData (): BindData<'T> = let bindFunc keyInput = KeyInputData.Create keyInput false |> x.MappedBindFunction |> (fun mappedBindResult -> mappedBindResult.ConvertToBindResult()) { KeyRemapMode = x.KeyRemapMode; BindFunction = bindFunc } /// Several types of MappedBindData<'T> need to take an action when a binding /// begins against themselves. This action needs to occur before the first /// KeyInput value is processed and hence they need a jump start. The most /// notable is IncrementalSearch which needs to enter 'Search' mode before /// processing KeyInput values so the cursor can be updated [<RequireQualifiedAccess>] type MappedBindDataStorage<'T> = /// Simple MappedBindData<'T> which doesn't require activation | Simple of MappedBindData: MappedBindData<'T> /// Complex MappedBindData<'T> which does require activation | Complex of CreateBindDataFunc: (unit -> MappedBindData<'T>) with /// Creates the MappedBindData member x.CreateMappedBindData () = match x with | Simple bindData -> bindData | Complex func -> func() /// Convert from a MappedBindDataStorage<'T> -> MappedBindDataStorage<'U>. /// The 'mapFunc' value will run on the final 'T' data if it eventually is /// completed member x.Convert mapFunc = match x with | Simple bindData -> Simple (bindData.Convert mapFunc) | Complex func -> Complex (fun () -> func().Convert mapFunc) /// Representation of binding of Command's to KeyInputSet values and flags which correspond /// to the execution of the command [<DebuggerDisplay("{ToString(),nq}")>] [<RequireQualifiedAccess>] type CommandBinding = /// KeyInputSet bound to a particular NormalCommand instance | NormalBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * NormalCommand: NormalCommand /// KeyInputSet bound to a complex NormalCommand instance | ComplexNormalBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * BindDataStorage: BindDataStorage<NormalCommand> /// KeyInputSet bound to a particular NormalCommand instance which takes a Motion Argument | MotionBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * Func: (MotionData -> NormalCommand) /// KeyInputSet bound to a particular VisualCommand instance | VisualBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * VisualCommand: VisualCommand /// KeyInputSet bound to an insert mode command | InsertBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * InsertCommand: InsertCommand /// KeyInputSet bound to a complex VisualCommand instance | ComplexVisualBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * BindDataStorage: BindDataStorage<VisualCommand> with /// The raw command inputs member x.KeyInputSet = match x with | NormalBinding (value, _, _) -> value | MotionBinding (value, _, _) -> value | VisualBinding (value, _, _) -> value | InsertBinding (value, _, _) -> value | ComplexNormalBinding (value, _, _) -> value | ComplexVisualBinding (value, _, _) -> value /// The kind of the Command member x.CommandFlags = match x with | NormalBinding (_, value, _) -> value | MotionBinding (_, value, _) -> value | VisualBinding (_, value, _) -> value | InsertBinding (_, value, _) -> value | ComplexNormalBinding (_, value, _) -> value | ComplexVisualBinding (_, value, _) -> value /// Is the Repeatable flag set member x.IsRepeatable = Util.IsFlagSet x.CommandFlags CommandFlags.Repeatable /// Is the HandlesEscape flag set member x.HandlesEscape = Util.IsFlagSet x.CommandFlags CommandFlags.HandlesEscape /// Is the Movement flag set member x.IsMovement = Util.IsFlagSet x.CommandFlags CommandFlags.Movement /// Is the Special flag set member x.IsSpecial = Util.IsFlagSet x.CommandFlags CommandFlags.Special override x.ToString() = System.String.Format("{0} -> {1}", x.KeyInputSet, x.CommandFlags) /// Used to execute commands and ICommandUtil = /// Run a normal command abstract RunNormalCommand: command: NormalCommand -> commandData: CommandData -> CommandResult /// Run a visual command abstract RunVisualCommand: command: VisualCommand -> commandData: CommandData -> visualSpan: VisualSpan -> CommandResult /// Run a insert command abstract RunInsertCommand: command: InsertCommand -> CommandResult /// Run a command abstract RunCommand: command: Command -> CommandResult type internal IInsertUtil = /// Run a insert command abstract RunInsertCommand: insertCommand: InsertCommand -> CommandResult /// Repeat the given edit series. abstract RepeatEdit: textChange: TextChange -> addNewLines: bool -> count: int -> unit /// Repeat the given edit series. abstract RepeatBlock: command: InsertCommand -> visualInsertKind: VisualInsertKind -> blockSpan: BlockSpan -> string option /// Signal that a new undo sequence is in effect abstract NewUndoSequence: unit -> unit /// Contains the stored information about a Visual Span. This instance *will* be /// stored for long periods of time and used to repeat a Command instance across /// multiple IVimBuffer instances so it must be buffer agnostic [<RequireQualifiedAccess>] type StoredVisualSpan = /// Storing a character wise span. Need to know the line count and the offset /// in the last line for the end. | Character of LineCount: int * LastLineMaxPositionCount: int /// Storing a line wise span just stores the count of lines | Line of Count: int /// Storing of a block span records the length of the span and the number of /// lines which should be affected by the Span | Block of Width: int * Height: int * EndOfLine: bool with /// Create a StoredVisualSpan from the provided VisualSpan value static member OfVisualSpan visualSpan = match visualSpan with | VisualSpan.Character characterSpan -> StoredVisualSpan.Character (characterSpan.LineCount, characterSpan.LastLineMaxPositionCount) | VisualSpan.Line range -> StoredVisualSpan.Line range.Count | VisualSpan.Block blockSpan -> StoredVisualSpan.Block (blockSpan.SpacesLength, blockSpan.Height, blockSpan.EndOfLine) /// Contains information about an executed Command. This instance *will* be stored /// for long periods of time and used to repeat a Command instance across multiple /// IVimBuffer instances so it simply cannot store any state specific to an /// ITextView instance. It must be completely agnostic of such information [<RequireQualifiedAccess>] type StoredCommand = /// The stored information about a NormalCommand | NormalCommand of NormalCommand: NormalCommand * CommandData: CommandData * CommandFlags: CommandFlags /// The stored information about a VisualCommand | VisualCommand of VisualCommand: VisualCommand * CommandData: CommandData * StoredVisualSpan: StoredVisualSpan * CommandFlags: CommandFlags /// The stored information about a InsertCommand | InsertCommand of InsertCommand: InsertCommand * CommandFlags: CommandFlags /// A Linked Command links together 2 other StoredCommand objects so they /// can be repeated together. | LinkedCommand of Left: StoredCommand * Right: StoredCommand with /// The CommandFlags associated with this StoredCommand member x.CommandFlags = match x with | NormalCommand (_, _, flags) -> flags | VisualCommand (_, _, _, flags) -> flags | InsertCommand (_, flags) -> flags | LinkedCommand (_, rightCommand) -> rightCommand.CommandFlags /// Returns the last command. For most StoredCommand values this is just an identity /// function but for LinkedCommand values it returns the right most member x.LastCommand = match x with | NormalCommand _ -> x | VisualCommand _ -> x | InsertCommand _ -> x | LinkedCommand (_, right) -> right.LastCommand /// Create a StoredCommand instance from the given Command value static member OfCommand command (commandBinding: CommandBinding) = match command with | Command.NormalCommand (command, data) -> StoredCommand.NormalCommand (command, data, commandBinding.CommandFlags) | Command.VisualCommand (command, data, visualSpan) -> let storedVisualSpan = StoredVisualSpan.OfVisualSpan visualSpan StoredCommand.VisualCommand (command, data, storedVisualSpan, commandBinding.CommandFlags) | Command.InsertCommand command -> StoredCommand.InsertCommand (command, commandBinding.CommandFlags) /// Flags about specific motions [<RequireQualifiedAccess>] [<System.Flags>] type MotionFlags = | None = 0x0 /// This type of motion can be used to move the caret | CaretMovement = 0x1 /// The motion function wants to specially handle the esape function. This is used /// on Complex motions such as / and ? | HandlesEscape = 0x2 /// Text object selection motions. These can be used for cursor movement inside of /// Visual Mode but otherwise need to be used only after operators. /// :help text-objects | TextObject = 0x4 /// Text object with line to character. Requires TextObject | TextObjectWithLineToCharacter = 0x8 /// Text object with always character. Requires TextObject | TextObjectWithAlwaysCharacter = 0x10 /// Text objcet with always line. Requires TextObject | TextObjectWithAlwaysLine = 0x20 /// Represents the types of MotionCommands which exist [<RequireQualifiedAccess>] type MotionBinding = /// Simple motion which comprises of a single KeyInput and a function which given /// a start point and count will produce the motion. None is returned in the /// case the motion is not valid | Static of KeyInputSet: KeyInputSet * MotionFlags: MotionFlags * Motion: Motion /// Complex motion commands take more than one KeyInput to complete. For example /// the f,t,F and T commands all require at least one additional input. | Dynamic of KeyInputSet: KeyInputSet * MotionFlags: MotionFlags * BindDataStorage: BindDataStorage<Motion> with member x.KeyInputSet = match x with | Static (keyInputSet, _, _) -> keyInputSet | Dynamic (keyInputSet, _, _) -> keyInputSet member x.MotionFlags = match x with | Static (_, flags, _) -> flags | Dynamic (_, flags, _) -> flags /// The information about the particular run of a Command type CommandRunData = { /// The binding which the command was invoked from CommandBinding: CommandBinding /// The Command which was run Command: Command /// The result of the Command Run CommandResult: CommandResult } type CommandRunDataEventArgs(_commandRunData: CommandRunData) = inherit System.EventArgs() member x.CommandRunData = _commandRunData -type CommandEventArgs(_command: string, _wasMapped: bool, _lineCommand: LineCommand) = +type CommandEventArgs(_rawCommand: string, _command: string, _wasMapped: bool, _lineCommand: LineCommand) = inherit System.EventArgs() + /// This is provided text that was executed. This can be both the abbreviated form of a command, say 'e', + /// or the expanded form 'edit'. + member x.RawCommand = _rawCommand + + /// This is the expanded command name which was executed. It will never be the abbreviated form. member x.Command = _command member x.LineCommand = _lineCommand member x.WasMapped = _wasMapped /// Responsible for binding key input to a Motion and MotionArgument tuple. Does /// not actually run the motions type IMotionCapture = /// Associated ITextView abstract TextView: ITextView /// Set of MotionBinding values supported abstract MotionBindings: MotionBinding list /// Get the motion and count starting with the given KeyInput abstract GetMotionAndCount: KeyInput -> BindResult<Motion * int option> /// Get the motion with the provided KeyInput abstract GetMotion: KeyInput -> BindResult<Motion> /// Responsible for managing a set of Commands and running them type ICommandRunner = /// Set of Commands currently supported. abstract Commands: CommandBinding seq /// Count of commands currently supported. abstract CommandCount: int /// In certain circumstances a specific type of key remapping needs to occur for input. This /// option will have the appropriate value in those circumstances. For example while processing /// the {char} argument to f,F,t or T the Language mapping will be used abstract KeyRemapMode: KeyRemapMode /// True when in the middle of a count operation abstract InCount: bool /// Is the command runner currently binding a command which needs to explicitly handle escape abstract IsHandlingEscape: bool /// True if waiting on more input abstract IsWaitingForMoreInput: bool /// True if the current command has a register associated with it abstract HasRegisterName: bool /// True if the current command has a count associated with it abstract HasCount: bool /// When HasRegister is true this has the associated RegisterName abstract RegisterName: RegisterName /// When HasCount is true this has the associated count abstract Count: int /// List of processed KeyInputs in the order in which they were typed abstract Inputs: KeyInput list /// Whether a command starts with the specified key input abstract DoesCommandStartWith: KeyInput -> bool /// Add a Command. If there is already a Command with the same name an exception will /// be raised abstract Add: CommandBinding -> unit /// Remove a command with the specified name abstract Remove: KeyInputSet -> unit /// Process the given KeyInput. If the command completed it will return a result. A /// None value implies more input is needed to finish the operation abstract Run: KeyInput -> BindResult<CommandRunData> /// If currently waiting for more input on a Command, reset to the /// initial state abstract ResetState: unit -> unit /// Raised when a command is successfully run [<CLIEvent>] abstract CommandRan: IDelegateEvent<System.EventHandler<CommandRunDataEventArgs>> [<Struct>] type KeyMapping = val private _left: KeyInputSet val private _right: KeyInputSet val private _allowRemap: bool val private _mode: KeyRemapMode new (left: KeyInputSet, right: KeyInputSet, allowRemap: bool, mode: KeyRemapMode) = { _left = left; _right = right; _allowRemap = allowRemap; _mode = mode } member x.Left = x._left member x.Right = x._right member x.AllowRemap = x._allowRemap member x.Mode = x._mode override x.ToString() = sprintf "%O - %O" x.Left x.Right type IVimKeyMap = abstract KeyMappings: KeyMapping seq /// Get the specified key mapping if it exists abstract GetKeyMapping: lhs: KeyInputSet * mode: KeyRemapMode -> KeyMapping option /// Get all mappings for the specified mode abstract GetKeyMappings: mode: KeyRemapMode -> KeyMapping seq /// Map the given key sequence without allowing for remaping abstract AddKeyMapping: lhs: KeyInputSet * rhs: KeyInputSet * allowRemap: bool * mode: KeyRemapMode -> unit /// Unmap the specified key sequence for the specified mode abstract RemoveKeyMapping: lhs: KeyInputSet * mode: KeyRemapMode -> bool /// Clear the Key mappings for the specified mode abstract ClearKeyMappings: mode: KeyRemapMode -> unit /// Clear the Key mappings for all modes abstract ClearKeyMappings: unit -> unit /// This operates similar to KeyNotationUtil.TryStringToKeyInputSet except that it will consider /// the <leader> notation as well. abstract ParseKeyNotation: notation: string -> KeyInputSet option type IVimGlobalKeyMap = inherit IVimKeyMap type IVimLocalKeyMap = inherit IVimKeyMap abstract GlobalKeyMap: IVimGlobalKeyMap /// Is the mapping of the 0 key currently enabled abstract IsZeroMappingEnabled: bool with get, set /// Get the specified key mapping if it exists abstract GetKeyMapping: lhs: KeyInputSet * mode: KeyRemapMode * includeGlobal: bool -> KeyMapping option /// Get the specified key mappings if they exists abstract GetKeyMappings: mode: KeyRemapMode * includeGlobal: bool -> KeyMapping seq /// Map the provided KeyInputSet for the given mode. abstract Map: lhs: KeyInputSet * mode: KeyRemapMode -> KeyMappingResult /// Map the provided KeyInputSet for the given mode. The allowRemap parameter will override /// the defined remapping behavior. abstract Map: lhs: KeyInputSet * allowRemap: bool * mode:KeyRemapMode -> KeyMappingResult /// Manages the digraph map for Vim type IDigraphMap = abstract Map: char -> char -> int -> unit abstract Unmap: char -> char -> unit abstract GetMapping: char -> char -> int option abstract Mappings: (char * char * int) seq abstract Clear: unit -> unit [<NoEquality>] [<NoComparison>] [<Struct>] type Abbreviation = val private _abbreviation: KeyInputSet val private _replacement: KeyInputSet val private _allowRemap: bool val private _mode: AbbreviationMode new (abbreviation: KeyInputSet, replacement: KeyInputSet, allowRemap: bool, mode: AbbreviationMode) = { _abbreviation = abbreviation; _replacement = replacement; _allowRemap = allowRemap; _mode = mode } member x.Abbreviation = x._abbreviation member x.Replacement = x._replacement member x.AllowRemap = x._allowRemap member x.Mode = x._mode override x.ToString() = sprintf "%O - %O" x.Abbreviation x.Replacement /// Information about a single abbreviation replace [<NoComparison>] [<NoEquality>] type AbbreviationResult = { /// The found Abbreviation that was replaced Abbreviation: Abbreviation /// The AbbreviationKind of the found abbrevitaion AbbreviationKind: AbbreviationKind /// The set of KeyInput values that should be used to replace the abbreviated text. /// Note: this can be different than Abbreviation.Replacement when key mappings are /// in play. AbbreviationResult.Replacement should be preferred. Replacement: KeyInputSet /// This contains the result of running the remap operation on Abbreviation.Replacement. ReplacementRemapResult: KeyMappingResult option /// The original text which was considered for the abbreviation OriginalText: string /// The KeyInput which triggered the abbreviation attempt. This will always be a non-keyword /// character. TriggerKeyInput: KeyInput /// The Span inside OriginalText which should be replaced by the abbreviation ReplacedSpan: Span } with member x.Mode = x.Abbreviation.Mode override x.ToString() = let key = x.Abbreviation.ToString() let value = (x.Replacement.Add x.TriggerKeyInput).ToString() let text = x.OriginalText.Substring(0, x.OriginalText.Length - key.Length) text + value type IVimAbbreviationMap = abstract Abbreviations: Abbreviation seq abstract AddAbbreviation: lhs: KeyInputSet * rhs: KeyInputSet * allowRemap: bool * mode: AbbreviationMode -> unit abstract GetAbbreviation: lhs: KeyInputSet * mode: AbbreviationMode -> Abbreviation option abstract GetAbbreviations: mode: AbbreviationMode -> Abbreviation seq abstract RemoveAbbreviation: lhs: KeyInputSet * mode: AbbreviationMode -> bool abstract ClearAbbreviations: mode: AbbreviationMode -> unit abstract ClearAbbreviations: unit -> unit type IVimGlobalAbbreviationMap = inherit IVimAbbreviationMap type IVimLocalAbbreviationMap = inherit IVimAbbreviationMap abstract GlobalAbbreviationMap: IVimGlobalAbbreviationMap abstract GetAbbreviation: lhs: KeyInputSet * mode: AbbreviationMode * includeGlobal: bool -> Abbreviation option abstract GetAbbreviations: mode: AbbreviationMode * includeGlobal: bool -> Abbreviation seq abstract Parse: text: string -> AbbreviationKind option abstract Abbreviate: text: string * triggerKeyInput: KeyInput * mode: AbbreviationMode -> AbbreviationResult option type MarkTextBufferEventArgs (_mark: Mark, _textBuffer: ITextBuffer) = inherit System.EventArgs() member x.Mark = _mark member x.TextBuffer = _textBuffer override x.ToString() = _mark.ToString() type MarkTextViewEventArgs (_mark: Mark, _textView: ITextView) = inherit System.EventArgs() member x.Mark = _mark member x.TextView = _textView override x.ToString() = _mark.ToString() /// Jump list information associated with an IVimBuffer. This is maintained as a forward /// and backwards traversable list of points with which to navigate to /// /// Technically Vim's implementation of a jump list can span across different /// buffers This is limited to just a single ITextBuffer. This is mostly due to Visual /// Studio's limitations in swapping out an ITextBuffer contents for a different file. It /// is possible but currently not a high priority here type IJumpList = /// Associated ITextView instance abstract TextView: ITextView /// Current value in the jump list. Will be None if we are not currently traversing the /// jump list abstract Current: VirtualSnapshotPoint option /// Current index into the jump list. Will be None if we are not currently traversing /// the jump list abstract CurrentIndex: int option /// True if we are currently traversing the list abstract IsTraversing: bool /// Get all of the jumps in the jump list. Returns in order of most recent to oldest abstract Jumps: VirtualSnapshotPoint list /// The SnapshotPoint when the last jump occurred abstract LastJumpLocation: VirtualSnapshotPoint option /// Add a given SnapshotPoint to the jump list. This will reset Current to point to /// the begining of the jump list abstract Add: VirtualSnapshotPoint -> unit /// Clear out all of the stored jump information. Removes all tracking information from /// the IJumpList abstract Clear: unit -> unit /// Move to the previous point in the jump list. This will fail if we are not traversing /// the list or at the end abstract MoveOlder: int -> bool /// Move to the next point in the jump list. This will fail if we are not traversing /// the list or at the start abstract MoveNewer: int -> bool /// Set the last jump location to the given line and column abstract SetLastJumpLocation: lineNumber: int -> offset: int -> unit /// Start a traversal of the list abstract StartTraversal: unit -> unit /// Raised when a mark is set [<CLIEvent>] abstract MarkSet: IDelegateEvent<System.EventHandler<MarkTextViewEventArgs>> type IIncrementalSearchSession = /// Key that uniquely identifies this session abstract Key: obj /// Whether or not the search has started abstract IsStarted: bool /// Whether or not the session is complete. True when the session has finished the search /// or was cancelled. abstract IsCompleted: bool /// When in the middle of a search this will return the SearchData for /// the search abstract SearchData: SearchData /// When a search is complete within the session this will hold the result abstract SearchResult: SearchResult option /// Start an incremental search in the ITextView abstract Start: unit -> BindData<SearchResult> /// Reset the search to the specified text abstract ResetSearch: searchText: string -> unit /// Cancel the session without completing abstract Cancel: unit -> unit /// This will resolve to SearchResult for the current value of SearchData once the /// search is complete abstract GetSearchResultAsync: unit -> Task<SearchResult> [<CLIEvent>] abstract SearchStart: IDelegateEvent<System.EventHandler<SearchDataEventArgs>> [<CLIEvent>] abstract SearchEnd: IDelegateEvent<System.EventHandler<SearchResultEventArgs>> [<CLIEvent>] abstract SessionComplete: IDelegateEvent<System.EventHandler<EventArgs>> type IncrementalSearchSessionEventArgs(_session: IIncrementalSearchSession) = inherit System.EventArgs() member x.Session = _session type IIncrementalSearch = /// The active IIncrementalSearchSession abstract ActiveSession: IIncrementalSearchSession option /// True when there is an IIncrementalSearchSession in progress abstract HasActiveSession: bool /// True when the search is in a paste wait state abstract InPasteWait: bool /// The ITextStructureNavigator used for finding 'word' values in the ITextBuffer abstract WordNavigator: ITextStructureNavigator abstract CurrentSearchData: SearchData abstract CurrentSearchText: string abstract CreateSession: searchPath: SearchPath -> IIncrementalSearchSession /// Cancel the active session if there is one. abstract CancelSession: unit -> unit [<CLIEvent>] abstract SessionCreated: IDelegateEvent<System.EventHandler<IncrementalSearchSessionEventArgs>> type RecordRegisterEventArgs(_register: Register, _isAppend: bool) = inherit System.EventArgs() member x.Register = _register member x.IsAppend = _isAppend /// Used to record macros in a Vim type IMacroRecorder = /// The current recording abstract CurrentRecording: KeyInput list option /// Is a macro currently recording abstract IsRecording: bool /// Start recording a macro into the specified Register. Will fail if the recorder /// is already recording abstract StartRecording: register: Register -> isAppend: bool -> unit /// Stop recording a macro. Will fail if it's not actually recording abstract StopRecording: unit -> unit /// Raised when a macro recording is started. Passes the Register where the recording /// will take place. The bool is whether the record is an append or not [<CLIEvent>] abstract RecordingStarted: IDelegateEvent<System.EventHandler<RecordRegisterEventArgs>> /// Raised when a macro recording is completed. [<CLIEvent>] abstract RecordingStopped: IDelegateEvent<System.EventHandler> [<RequireQualifiedAccess>] type ProcessResult = /// The input was processed and provided the given ModeSwitch | Handled of ModeSwitch: ModeSwitch /// The input was processed but more input is needed in order to complete /// an operation | HandledNeedMoreInput /// The operation did not handle the input | NotHandled /// The input was processed and resulted in an error | Error /// Is this any type of mode switch member x.IsAnySwitch = match x with | Handled modeSwitch -> match modeSwitch with | ModeSwitch.NoSwitch -> false | ModeSwitch.SwitchMode _ -> true | ModeSwitch.SwitchModeWithArgument _ -> true | ModeSwitch.SwitchPreviousMode -> true | ModeSwitch.SwitchModeOneTimeCommand _ -> true | HandledNeedMoreInput -> false | NotHandled -> false | Error -> false /// Is this any type of switch to a visual mode member x.IsAnySwitchToVisual = match x with | ProcessResult.Handled modeSwitch -> match modeSwitch with | ModeSwitch.SwitchMode modeKind -> VisualKind.IsAnyVisualOrSelect modeKind | ModeSwitch.SwitchModeWithArgument(modeKind, _) -> VisualKind.IsAnyVisualOrSelect modeKind | ModeSwitch.SwitchModeOneTimeCommand modeKind -> VisualKind.IsAnyVisualOrSelect modeKind | _ -> false | _ -> false // Is this a switch to command mode? member x.IsAnySwitchToCommand = match x with | ProcessResult.Handled modeSwitch -> match modeSwitch with | ModeSwitch.SwitchMode modeKind -> modeKind = ModeKind.Command | ModeSwitch.SwitchModeWithArgument (modeKind, _) -> modeKind = ModeKind.Command | _ -> false | _ -> false /// Did this actually handle the KeyInput member x.IsAnyHandled = match x with | Handled _ -> true | HandledNeedMoreInput -> true | Error -> true | NotHandled -> false /// Is this a successfully handled value? member x.IsHandledSuccess = match x with | Handled _ -> true | HandledNeedMoreInput -> true | Error -> false | NotHandled -> false static member OfModeKind kind = let switch = ModeSwitch.SwitchMode kind Handled switch /// Create a ProcessResult from the given CommandResult value static member OfCommandResult commandResult = match commandResult with | CommandResult.Completed modeSwitch -> Handled modeSwitch | CommandResult.Error -> Error /// Create a CommandResult from the given ProcessResult value diff --git a/Src/VimCore/Interpreter_Interpreter.fs b/Src/VimCore/Interpreter_Interpreter.fs index db5b6a9..f2360ec 100644 --- a/Src/VimCore/Interpreter_Interpreter.fs +++ b/Src/VimCore/Interpreter_Interpreter.fs @@ -2075,572 +2075,572 @@ type VimInterpreter _vimData.LastShellCommand <- Some command // Prepend the shell flag before the other arguments. let workingDirectory = _vimBufferData.WorkingDirectory let shell = _globalSettings.Shell let command = if _globalSettings.ShellFlag.Length > 0 then sprintf "%s %s" _globalSettings.ShellFlag command else command if isReadCommand then x.RunWithPointAfterOrDefault lineRange DefaultLineRange.CurrentLine (fun point -> let results = _vimHost.RunCommand workingDirectory shell command StringUtil.Empty let status = results.Error let status = EditUtil.RemoveEndingNewLine status _statusUtil.OnStatus status let output = EditUtil.SplitLines results.Output x.RunReadCore point output) else if lineRange = LineRangeSpecifier.None then let results = _vimHost.RunCommand workingDirectory shell command StringUtil.Empty let status = results.Output + results.Error let status = EditUtil.RemoveEndingNewLine status _statusUtil.OnStatus status else x.RunWithLineRangeOrDefault lineRange DefaultLineRange.None (fun lineRange -> _commonOperations.FilterLines lineRange command) // Build up the actual command replacing any non-escaped ! with the previous // shell command let builder = System.Text.StringBuilder() let rec inner index afterBackslash = if index >= command.Length then builder.ToString() |> doRun else let current = command.[index] if current = '\\' && (index + 1) < command.Length then let next = command.[index + 1] builder.AppendChar next // It seems odd to escape ! after an escaped backslash but it's // specifically called out in the documentation for :shell let afterBackslash = next = '\\' inner (index + 2) afterBackslash elif current = '!' && not afterBackslash then match _vimData.LastShellCommand with | None -> _statusUtil.OnError Resources.Common_NoPreviousShellCommand | Some previousCommand -> builder.AppendString previousCommand inner (index + 1) false else builder.AppendChar current inner (index + 1) false inner 0 false /// Shift the given line range to the left member x.RunShiftLeft lineRange count = x.RunWithLineRangeOrDefault lineRange DefaultLineRange.CurrentLine (fun lineRange -> _commonOperations.ShiftLineRangeLeft lineRange count) /// Shift the given line range to the right member x.RunShiftRight lineRange count = x.RunWithLineRangeOrDefault lineRange DefaultLineRange.CurrentLine (fun lineRange -> _commonOperations.ShiftLineRangeRight lineRange count) /// Run the :sort command member x.RunSort lineRange reverseOrder flags pattern = x.RunWithLineRangeOrDefault lineRange DefaultLineRange.EntireBuffer (fun lineRange -> _commonOperations.SortLines lineRange reverseOrder flags pattern) /// Run the :source command member x.RunSource hasBang filePath = if hasBang then _statusUtil.OnError (Resources.Interpreter_OptionNotSupported "!") else let filePath = x.ResolveVimPath filePath match _fileSystem.ReadAllLines filePath with | None -> _statusUtil.OnError (Resources.Common_CouldNotOpenFile filePath) | Some lines -> let bag = new DisposableBag() let errorList = List<string>() try _vimBuffer.ErrorMessage |> Observable.subscribe (fun e -> errorList.Add(e.Message)) |> bag.Add x.RunScript lines finally bag.DisposeAll() if errorList.Count <> 0 then seq { let message = Resources.Interpreter_ErrorsSourcing filePath |> _statusUtil.NotateMessage yield message yield! errorList } |> _vimBufferData.StatusUtil.OnStatusLong /// Run the :stopinsert command member x.RunStopInsert () = if _vimBuffer.ModeKind = ModeKind.Insert then _vimBuffer.SwitchMode ModeKind.Normal ModeArgument.None |> ignore /// Split the window member x.RunSplit behavior fileOptions commandOption = let SplitArgumentsAreValid fileOptions commandOption = if not (List.isEmpty fileOptions) then _statusUtil.OnError (Resources.Interpreter_OptionNotSupported "[++opt]") false elif Option.isSome commandOption then _statusUtil.OnError (Resources.Interpreter_OptionNotSupported "[++cmd]") false else true if SplitArgumentsAreValid fileOptions commandOption then behavior _textView else () /// Run the substitute command. member x.RunSubstitute lineRange pattern replace flags = // Called to initialize the data and move to a confirm style substitution. Have to find the first match // before passing off to confirm let setupConfirmSubstitute (range: SnapshotLineRange) (data: SubstituteData) = let regex = VimRegexFactory.CreateForSubstituteFlags data.SearchPattern _globalSettings data.Flags match regex with | None -> _statusUtil.OnError (Resources.Common_PatternNotFound data.SearchPattern) | Some regex -> let firstMatch = range.Lines |> Seq.map (fun line -> line.ExtentIncludingLineBreak) |> Seq.tryPick (fun span -> RegexUtil.MatchSpan span regex.Regex) match firstMatch with | None -> _statusUtil.OnError (Resources.Common_PatternNotFound data.SearchPattern) | Some(span,_) -> let arg = ModeArgument.Substitute (span, range, data) _vimBuffer.SwitchMode ModeKind.SubstituteConfirm arg |> ignore // Check for the UsePrevious flag and update the flags as appropriate. Make sure // to bitwise or them against the new flags let flags = if Util.IsFlagSet flags SubstituteFlags.UsePreviousFlags then match _vimData.LastSubstituteData with | None -> SubstituteFlags.None | Some data -> (Util.UnsetFlag flags SubstituteFlags.UsePreviousFlags) ||| data.Flags else flags // Get the actual pattern to use let pattern = if pattern = "" then _vimData.LastSearchData.Pattern else // If a pattern is given then it is the one that we will use pattern x.RunWithLineRangeOrDefault lineRange DefaultLineRange.CurrentLine (fun lineRange -> if Util.IsFlagSet flags SubstituteFlags.Confirm then let data = { SearchPattern = pattern; Substitute = replace; Flags = flags} setupConfirmSubstitute lineRange data // If confirming, record the last patterns now. _vimData.LastSubstituteData <- Some data _vimData.LastSearchData <- SearchData(pattern, SearchPath.Forward) else _commonOperations.Substitute pattern replace lineRange flags) /// Run substitute using the pattern and replace values from the last substitute member x.RunSubstituteRepeatLast lineRange flags = let pattern, replace = match _vimData.LastSubstituteData with | None -> "", "" | Some substituteData -> substituteData.SearchPattern, substituteData.Substitute x.RunSubstitute lineRange pattern replace flags member x.RunTabNew symbolicPath = let filePath = x.InterpretSymbolicPath symbolicPath let resolvedFilePath = x.ResolveVimPath filePath _commonOperations.LoadFileIntoNewWindow resolvedFilePath (Some 0) None |> ignore member x.RunOnly() = _vimHost.CloseAllOtherWindows _textView member x.RunTabOnly() = _vimHost.CloseAllOtherTabs _textView /// Run the undo command member x.RunUndo() = _commonOperations.Undo 1 /// Run the unlet command member x.RunUnlet ignoreMissing nameList = let rec func nameList = match nameList with | [] -> () | name :: rest -> let removed = _variableMap.Remove(name) if not removed && not ignoreMissing then let msg = Resources.Interpreter_NoSuchVariable name _statusUtil.OnError msg else func rest func nameList /// Unmap the specified key notation in all of the listed modes member x.RunUnmapKeys keyNotation keyRemapModes mapArgumentList = let keyMap, mapArgumentList = x.GetKeyMap mapArgumentList if not (List.isEmpty mapArgumentList) then _statusUtil.OnError (Resources.Interpreter_OptionNotSupported "map special arguments") else match keyMap.ParseKeyNotation keyNotation with | Some key -> let mutable succeeded = true; for keyRemapMode in keyRemapModes do // The unmap operation by default unmaps the LHS. If the argument doesn't match any // LHS then all mappings where the argument matches the RHS are removed. if not (keyMap.RemoveKeyMapping(key, keyRemapMode)) then let all = keyMap.GetKeyMappings(keyRemapMode) |> Seq.filter (fun x -> x.Right = key) |> List.ofSeq if all.IsEmpty then succeeded <- false else for keyMapping in all do keyMap.RemoveKeyMapping(keyMapping.Left, keyRemapMode) |> ignore if not succeeded then _statusUtil.OnError Resources.CommandMode_NoSuchMapping | None -> _statusUtil.OnError Resources.Parser_InvalidArgument member x.RunVersion() = let msg = sprintf "VsVim Version %s" VimConstants.VersionNumber _statusUtil.OnStatus msg member x.RunHostCommand hasBang command argument = _vimHost.RunHostCommand _textView command argument if hasBang && not _textView.Selection.IsEmpty then // When clearing the selection after a host command, move the caret // to the start of the selection because the selected text usually // represents a "thing" (such as an identifier or group of text // lines). The caret resting on the start of that thing better // mimics the selection concept than putting the caret at the end // of the thing. let start = _textView.Selection.Start TextViewUtil.ClearSelection _textView TextViewUtil.MoveCaretToVirtualPoint _textView start member x.RunWrite lineRange hasBang fileOptionList filePath = x.RunWithLineRangeOrDefault lineRange DefaultLineRange.EntireBuffer (fun lineRange -> let filePath = match filePath with | Some filePath -> Some (x.ResolveVimPath filePath) | None -> None if not (List.isEmpty fileOptionList) then _statusUtil.OnError (Resources.Interpreter_OptionNotSupported "[++opt]") else match filePath with | Some filePath -> let text = lineRange.ExtentIncludingLineBreak.GetText() _vimHost.SaveTextAs text filePath |> ignore | None -> if not hasBang && _vimHost.IsReadOnly _textBuffer then _statusUtil.OnError Resources.Interpreter_ReadOnlyOptionIsSet else _vimHost.Save _textBuffer |> ignore) /// Run the 'wall' or 'wqall' command member x.RunWriteAll hasBang andQuit = // Write a buffer and return success or failure. let writeDirtyBuffer (vimBuffer: IVimBuffer) = if not hasBang && _vimHost.IsReadOnly vimBuffer.TextBuffer then _statusUtil.OnError Resources.Interpreter_ReadOnlyOptionIsSet false else _vimHost.Save vimBuffer.TextBuffer // Try to write all dirty buffers. let succeeded = _vim.VimBuffers |> Seq.filter (fun vimBuffer -> _vimHost.IsDirty vimBuffer.TextBuffer) |> Seq.map writeDirtyBuffer |> Seq.filter (fun succeeded -> not succeeded) |> Seq.isEmpty if andQuit then if succeeded then _vimHost.Quit() else _statusUtil.OnError Resources.Common_NoWriteSinceLastChange /// Yank the specified line range into the register. This is done in a /// linewise fashion member x.RunYank registerName lineRange count = x.RunWithLineRangeOrDefault lineRange DefaultLineRange.CurrentLine (fun lineRange -> // If the user specified a count then that count is applied to the end // of the specified line range let lineRange = match count with | None -> lineRange | Some count -> SnapshotLineRangeUtil.CreateForLineAndMaxCount lineRange.LastLine count let stringData = StringData.OfSpan lineRange.ExtentIncludingLineBreak let value = _commonOperations.CreateRegisterValue x.CaretPoint stringData OperationKind.LineWise _commonOperations.SetRegisterValue registerName RegisterOperation.Yank value) /// Run the specified LineCommand member x.RunLineCommand lineCommand = let cantRun () = _statusUtil.OnError Resources.Interpreter_Error match lineCommand with | LineCommand.Abbreviate (lhs, rhs, allowRemap, modeList, isLocal) -> x.RunAbbreviate lhs rhs allowRemap modeList isLocal | LineCommand.AbbreviateClear (modeList, isLocal) -> x.RunAbbreviateClear modeList isLocal | LineCommand.AddAutoCommand autoCommandDefinition -> x.RunAddAutoCommand autoCommandDefinition | LineCommand.Behave model -> x.RunBehave model | LineCommand.Call callInfo -> x.RunCall callInfo | LineCommand.ChangeDirectory path -> x.RunChangeDirectory path | LineCommand.ChangeLocalDirectory path -> x.RunChangeLocalDirectory path | LineCommand.ClearKeyMap (keyRemapModes, mapArgumentList) -> x.RunClearKeyMap keyRemapModes mapArgumentList | LineCommand.Close hasBang -> x.RunClose hasBang | LineCommand.Compose (lineCommand1, lineCommand2) -> x.RunCompose lineCommand1 lineCommand2 | LineCommand.CopyTo (sourceLineRange, destLineRange, count) -> x.RunCopyTo sourceLineRange destLineRange count | LineCommand.CSharpScript callInfo -> x.RunCSharpScript(callInfo, createEachTime = false) | LineCommand.CSharpScriptCreateEachTime callInfo -> x.RunCSharpScript(callInfo, createEachTime = true) | LineCommand.Digraphs digraphList -> x.RunDigraphs digraphList | LineCommand.DisplayAbbreviation (modes, lhs) -> x.RunDisplayAbbreviation modes lhs | LineCommand.DisplayKeyMap (keyRemapModes, keyNotationOption) -> x.RunDisplayKeyMap keyRemapModes keyNotationOption | LineCommand.DisplayRegisters nameList -> x.RunDisplayRegisters nameList | LineCommand.DisplayLet variables -> x.RunDisplayLet variables | LineCommand.DisplayLines (lineRange, lineCommandFlags) -> x.RunDisplayLines lineRange lineCommandFlags | LineCommand.DisplayMarks marks -> x.RunDisplayMarks marks | LineCommand.Delete (lineRange, registerName) -> x.RunDelete lineRange registerName | LineCommand.DeleteMarks marks -> x.RunDeleteMarks marks | LineCommand.DeleteAllMarks -> x.RunDeleteAllMarks() | LineCommand.Echo expression -> x.RunEcho expression | LineCommand.Edit (hasBang, fileOptions, commandOption, filePath) -> x.RunEdit hasBang fileOptions commandOption filePath | LineCommand.Else -> cantRun () | LineCommand.ElseIf _ -> cantRun () | LineCommand.Execute expression -> x.RunExecute expression | LineCommand.Function func -> x.RunFunction func | LineCommand.FunctionStart _ -> cantRun () | LineCommand.FunctionEnd _ -> cantRun () | LineCommand.Files -> x.RunFiles() | LineCommand.Fold lineRange -> x.RunFold lineRange | LineCommand.Global (lineRange, pattern, matchPattern, lineCommand) -> x.RunGlobal lineRange pattern matchPattern lineCommand | LineCommand.Help subject -> x.RunHelp subject | LineCommand.History -> x.RunHistory() | LineCommand.IfStart _ -> cantRun () | LineCommand.IfEnd -> cantRun () | LineCommand.If conditionalBlock -> x.RunIf conditionalBlock | LineCommand.GoToFirstTab -> x.RunGoToFirstTab() | LineCommand.GoToLastTab -> x.RunGoToLastTab() | LineCommand.GoToNextTab count -> x.RunGoToNextTab count | LineCommand.GoToPreviousTab count -> x.RunGoToPreviousTab count | LineCommand.HorizontalSplit (lineRange, fileOptions, commandOptions) -> x.RunSplit _vimHost.SplitViewHorizontally fileOptions commandOptions | LineCommand.HostCommand (hasBang, command, argument) -> x.RunHostCommand hasBang command argument | LineCommand.Join (lineRange, joinKind) -> x.RunJoin lineRange joinKind | LineCommand.JumpToLastLine lineRange -> x.RunJumpToLastLine lineRange | LineCommand.Let (name, value) -> x.RunLet name value | LineCommand.LetEnvironment (name, value) -> x.RunLetEnvironment name value | LineCommand.LetRegister (name, value) -> x.RunLetRegister name value | LineCommand.Make (hasBang, arguments) -> x.RunMake hasBang arguments | LineCommand.MapKeys (leftKeyNotation, rightKeyNotation, keyRemapModes, allowRemap, mapArgumentList) -> x.RunMapKeys leftKeyNotation rightKeyNotation keyRemapModes allowRemap mapArgumentList | LineCommand.MoveTo (sourceLineRange, destLineRange, count) -> x.RunMoveTo sourceLineRange destLineRange count | LineCommand.NavigateToListItem (listKind, navigationKind, argument, hasBang) -> x.RunNavigateToListItem listKind navigationKind argument hasBang | LineCommand.NoHighlightSearch -> x.RunNoHighlightSearch() | LineCommand.Nop -> () | LineCommand.Normal (lineRange, command) -> x.RunNormal lineRange command | LineCommand.Only -> x.RunOnly() | LineCommand.OpenListWindow listKind -> x.RunOpenListWindow listKind | LineCommand.ParseError msg -> x.RunParseError msg | LineCommand.PrintCurrentDirectory -> x.RunPrintCurrentDirectory() | LineCommand.PutAfter (lineRange, registerName) -> x.RunPut lineRange registerName true | LineCommand.PutBefore (lineRange, registerName) -> x.RunPut lineRange registerName false | LineCommand.Quit hasBang -> x.RunQuit hasBang | LineCommand.QuitAll hasBang -> x.RunQuitAll hasBang | LineCommand.QuitWithWrite (lineRange, hasBang, fileOptions, filePath) -> x.RunQuitWithWrite lineRange hasBang fileOptions filePath | LineCommand.ReadCommand (lineRange, command) -> x.RunReadCommand lineRange command | LineCommand.ReadFile (lineRange, fileOptionList, filePath) -> x.RunReadFile lineRange fileOptionList filePath | LineCommand.Redo -> x.RunRedo() | LineCommand.RemoveAutoCommands autoCommandDefinition -> x.RemoveAutoCommands autoCommandDefinition | LineCommand.Retab (lineRange, hasBang, tabStop) -> x.RunRetab lineRange hasBang tabStop | LineCommand.Search (lineRange, path, pattern) -> x.RunSearch lineRange path pattern | LineCommand.Set argumentList -> x.RunSet argumentList | LineCommand.Shell -> x.RunShell() | LineCommand.ShellCommand (lineRange, command) -> x.RunShellCommand lineRange command | LineCommand.ShiftLeft (lineRange, count) -> x.RunShiftLeft lineRange count | LineCommand.ShiftRight (lineRange, count) -> x.RunShiftRight lineRange count | LineCommand.Sort (lineRange, hasBang, flags, pattern) -> x.RunSort lineRange hasBang flags pattern | LineCommand.Source (hasBang, filePath) -> x.RunSource hasBang filePath | LineCommand.StopInsert -> x.RunStopInsert() | LineCommand.Substitute (lineRange, pattern, replace, flags) -> x.RunSubstitute lineRange pattern replace flags | LineCommand.SubstituteRepeat (lineRange, substituteFlags) -> x.RunSubstituteRepeatLast lineRange substituteFlags | LineCommand.TabNew filePath -> x.RunTabNew filePath | LineCommand.TabOnly -> x.RunTabOnly() | LineCommand.Unabbreviate (keyNotation, modeList, isLocal) -> x.RunUnabbreviate keyNotation modeList isLocal | LineCommand.Undo -> x.RunUndo() | LineCommand.Unlet (ignoreMissing, nameList) -> x.RunUnlet ignoreMissing nameList | LineCommand.UnmapKeys (keyNotation, keyRemapModes, mapArgumentList) -> x.RunUnmapKeys keyNotation keyRemapModes mapArgumentList | LineCommand.Version -> x.RunVersion() | LineCommand.VerticalSplit (lineRange, fileOptions, commandOptions) -> x.RunSplit _vimHost.SplitViewVertically fileOptions commandOptions | LineCommand.VimGrep (count, hasBang, pattern, flags, filePattern) -> x.RunVimGrep count hasBang pattern flags filePattern | LineCommand.VimHelp subject -> x.RunVimHelp subject | LineCommand.Write (lineRange, hasBang, fileOptionList, filePath) -> x.RunWrite lineRange hasBang fileOptionList filePath | LineCommand.WriteAll (hasBang, andQuit) -> x.RunWriteAll hasBang andQuit | LineCommand.Yank (lineRange, registerName, count) -> x.RunYank registerName lineRange count member x.RunWithLineRange lineRangeSpecifier (func: SnapshotLineRange -> unit) = x.RunWithLineRangeOrDefault lineRangeSpecifier DefaultLineRange.None func member x.RunWithLineRangeOrDefault (lineRangeSpecifier: LineRangeSpecifier) defaultLineRange (func: SnapshotLineRange -> unit) = match x.GetLineRangeOrDefault lineRangeSpecifier defaultLineRange with | None -> _statusUtil.OnError Resources.Range_Invalid | Some lineRange -> func lineRange /// Convert a loose line range specifier into a line range and run the /// specified function on it member x.RunWithLooseLineRangeOrDefault (lineRangeSpecifier: LineRangeSpecifier) defaultLineRange (func: SnapshotLineRange -> unit) = let strictLineRangeSpecifier = x.GetStrictLineRangeSpecifier lineRangeSpecifier x.RunWithLineRangeOrDefault strictLineRangeSpecifier defaultLineRange func /// Get a strict line range specifier from a loose one member x.GetStrictLineRangeSpecifier looseLineRangeSpecifier = match looseLineRangeSpecifier with | LineRangeSpecifier.SingleLine looseLineSpecifier -> let strictLineSpecifier = x.GetStrictLineSpecifier looseLineSpecifier LineRangeSpecifier.SingleLine strictLineSpecifier | LineRangeSpecifier.Range (looseStartLineSpecifier, looseEndLineSpecifier, moveCaret) -> let strictStartLineSpecifier = x.GetStrictLineSpecifier looseStartLineSpecifier let strictEndLineSpecifier = x.GetStrictLineSpecifier looseEndLineSpecifier LineRangeSpecifier.Range (strictStartLineSpecifier, strictEndLineSpecifier, moveCaret) | otherLineRangeSpecifier -> otherLineRangeSpecifier /// Get a strict line specifier from a loose one (a loose line specifier /// tolerates line number that are too large) member x.GetStrictLineSpecifier looseLineSpecifier = match looseLineSpecifier with | LineSpecifier.Number number -> let lastLineNumber = SnapshotUtil.GetLastNormalizedLineNumber x.CurrentSnapshot LineSpecifier.Number (min number (lastLineNumber + 1)) | otherLineSpecifier -> otherLineSpecifier member x.RunWithPointAfterOrDefault (lineRangeSpecifier: LineRangeSpecifier) defaultLineRange (func: SnapshotPoint -> unit) = match x.GetPointAfterOrDefault lineRangeSpecifier defaultLineRange with | None -> _statusUtil.OnError Resources.Range_Invalid | Some point -> func point // Actually parse and run all of the commands which are included in the script member x.RunScript lines = let parser = Parser(_globalSettings, _vimData, lines) let previousContextLineNumber = _statusUtil.ContextLineNumber try while not parser.IsDone do let contextLineNumber = parser.ContextLineNumber let lineCommand = parser.ParseNextCommand() _statusUtil.ContextLineNumber <- if lines.Length <> 1 then Some contextLineNumber else None x.RunLineCommand lineCommand |> ignore finally _statusUtil.ContextLineNumber <- previousContextLineNumber member x.InterpretSymbolicPath (symbolicPath: SymbolicPath) = let rec inner (sb:System.Text.StringBuilder) sp = match sp with | SymbolicPathComponent.Literal literal::tail -> sb.AppendString literal inner sb tail | SymbolicPathComponent.CurrentFileName modifiers::tail -> let path = match modifiers with | FileNameModifier.PathFull::tail -> x.ApplyFileNameModifiers _vimBufferData.CurrentFilePath tail | _ -> x.ApplyFileNameModifiers _vimBufferData.CurrentRelativeFilePath modifiers path |> sb.AppendString inner sb tail | SymbolicPathComponent.AlternateFileName (n, modifiers)::tail -> let fileHistory = _vimData.FileHistory let fileName = if n >= fileHistory.Count then None else Some fileHistory.Items.[n] let path = match modifiers with | FileNameModifier.PathFull::tail -> x.ApplyFileNameModifiers fileName tail | _ -> let relativeFileName = match fileName with | None -> None | Some filePath -> SystemUtil.StripPathPrefix x.CurrentDirectory filePath |> Some x.ApplyFileNameModifiers relativeFileName modifiers path |> sb.AppendString inner sb tail | [] -> () let builder = System.Text.StringBuilder() inner builder symbolicPath builder.ToString() member x.TryExpandCommandName(shortCommandName, commandName: outref<string>) = let parser = Parser(_globalSettings, _vimData) - match parser.TryExpand shortCommandName with + match parser.TryExpandCommandName shortCommandName with | Some fullCommandName -> commandName <- fullCommandName true | None -> false member x.ApplyFileNameModifiers path modifiers : string = let rec inner path modifiers : string = match path with | "" -> "" | _ -> match modifiers with | FileNameModifier.Head::tail -> match Path.GetDirectoryName path with | "" -> "." | d -> inner d tail | FileNameModifier.Tail::tail -> inner (Path.GetFileName path) tail | FileNameModifier.Root::tail when path.StartsWith(".") -> inner path tail | FileNameModifier.Root::tail -> let s = path.Substring(0, path.Length - (Path.GetExtension path).Length) inner s tail | FileNameModifier.Extension::_ when path.StartsWith(".") -> "" | FileNameModifier.Extension::tail -> let tailNew = List.skipWhile (fun m -> m = FileNameModifier.Extension) tail let count = 1 + (tail.Length - tailNew.Length) let exts = Array.tail ((Path.GetFileName path).Split('.')) let ext = Array.skip (exts.Length - count) exts |> String.concat "." inner ext tailNew | _ -> path match path with | None -> "" | Some path -> inner path modifiers interface IVimInterpreter with member x.GetLine(lineSpecifier) = x.GetLine lineSpecifier member x.GetLineRange(lineRange) = x.GetLineRange lineRange member x.RunLineCommand(lineCommand) = x.RunLineCommand lineCommand member x.RunExpression(expression) = x.RunExpression expression member x.EvaluateExpression(text) = x.EvaluateExpression text member x.RunScript(lines) = x.RunScript lines member x.TryExpandCommandName(shortCommandName, commandName: outref<string>) = x.TryExpandCommandName(shortCommandName, &commandName) [<Export(typeof<IVimInterpreterFactory>)>] type VimInterpreterFactory [<ImportingConstructor>] ( _commonOperationsFactory: ICommonOperationsFactory, _foldManagerFactory: IFoldManagerFactory, _bufferTrackingService: IBufferTrackingService ) = member x.CreateVimInterpreter (vimBuffer: IVimBuffer) fileSystem = let commonOperations = _commonOperationsFactory.GetCommonOperations vimBuffer.VimBufferData let foldManager = _foldManagerFactory.GetFoldManager vimBuffer.TextView let interpreter = VimInterpreter(vimBuffer, commonOperations, foldManager, fileSystem, _bufferTrackingService) interpreter :> IVimInterpreter interface IVimInterpreterFactory with member x.CreateVimInterpreter vimBuffer fileSystem = x.CreateVimInterpreter vimBuffer fileSystem diff --git a/Src/VimCore/Interpreter_Parser.fs b/Src/VimCore/Interpreter_Parser.fs index bbe5c13..4764244 100644 --- a/Src/VimCore/Interpreter_Parser.fs +++ b/Src/VimCore/Interpreter_Parser.fs @@ -1,974 +1,974 @@ #light namespace Vim.Interpreter open Vim open System.Collections.Generic open StringBuilderExtensions [<RequireQualifiedAccess>] type internal ParseRegisterName = | All | NoNumbered [<RequireQualifiedAccess>] type internal ParseResult<'T> = | Succeeded of Value: 'T | Failed of Error: string with member x.Map (mapFunc: 'T -> ParseResult<'U>) = match x with | ParseResult.Failed msg -> ParseResult.Failed msg | ParseResult.Succeeded value -> mapFunc value module internal ParseResultUtil = let Map (parseResult: ParseResult<'T>) mapFunc = parseResult.Map mapFunc let ConvertToLineCommand (parseResult: ParseResult<LineCommand>) = match parseResult with | ParseResult.Failed msg -> LineCommand.ParseError msg | ParseResult.Succeeded lineCommand -> lineCommand type internal ParseResultBuilder ( _parser: Parser, _errorMessage: string ) = new (parser) = ParseResultBuilder(parser, Resources.Parser_Error) /// Bind a ParseResult value member x.Bind (parseResult: ParseResult<'T>, (rest: 'T -> ParseResult<'U>)) = match parseResult with | ParseResult.Failed msg -> ParseResult.Failed msg | ParseResult.Succeeded value -> rest value /// Bind an option value member x.Bind (parseValue: 'T option, (rest: 'T -> ParseResult<'U>)) = match parseValue with | None -> ParseResult.Failed _errorMessage | Some value -> rest value member x.Return (value: 'T) = ParseResult.Succeeded value member x.Return (parseResult: ParseResult<'T>) = match parseResult with | ParseResult.Failed msg -> ParseResult.Failed msg | ParseResult.Succeeded value -> ParseResult.Succeeded value member x.Return (msg: string) = ParseResult.Failed msg member x.ReturnFrom value = value member x.Zero () = ParseResult.Failed _errorMessage and LineCommandBuilder ( _parser: Parser, _errorMessage: string ) = new (parser) = LineCommandBuilder(parser, Resources.Parser_Error) /// Bind a ParseResult value member x.Bind (parseResult: ParseResult<'T>, rest) = match parseResult with | ParseResult.Failed msg -> _parser.ParseError msg | ParseResult.Succeeded value -> rest value /// Bind an option value member x.Bind (parseValue: 'T option, rest) = match parseValue with | None -> _parser.ParseError _errorMessage | Some value -> rest value member x.Return (value: LineCommand) = value member x.Return (parseResult: ParseResult<LineCommand>) = match parseResult with | ParseResult.Failed msg -> _parser.ParseError msg | ParseResult.Succeeded lineCommand -> lineCommand member x.Return (msg: string) = _parser.ParseError msg member x.ReturnFrom value = value member x.Zero () = _parser.ParseError _errorMessage and [<Sealed>] internal Parser ( _globalSettings: IVimGlobalSettings, _vimData: IVimData ) as this = let _parseResultBuilder = ParseResultBuilder(this) let _lineCommandBuilder = LineCommandBuilder(this) let _tokenizer = Tokenizer("", TokenizerFlags.None) let mutable _lines = [|""|] let mutable _lineIndex = 0 /// The set of supported line commands paired with their abbreviation static let s_LineCommandNamePair = [ ("autocmd", "au") ("behave", "be") ("call", "cal") ("cd", "cd") ("chdir", "chd") ("close", "clo") ("copy", "co") ("csx", "cs") ("csxe", "csxe") ("delete","d") ("delmarks", "delm") ("digraphs", "dig") ("display","di") ("echo", "ec") ("edit", "e") ("else", "el") ("execute", "exe") ("elseif", "elsei") ("endfunction", "endf") ("endif", "en") ("exit", "exi") ("fold", "fo") ("function", "fu") ("global", "g") ("help", "h") ("vimhelp", "vimh") ("history", "his") ("if", "if") ("join", "j") ("lcd", "lc") ("lchdir", "lch") ("list", "l") ("let", "let") ("move", "m") ("make", "mak") ("marks", "") ("nohlsearch", "noh") ("normal", "norm") ("number", "nu") ("only", "on") ("pwd", "pw") ("print", "p") ("Print", "P") ("put", "pu") ("quit", "q") ("qall", "qa") ("quitall", "quita") ("read", "r") ("redo", "red") ("registers", "reg") ("retab", "ret") ("set", "se") ("shell", "sh") ("sort", "sor") ("source","so") ("split", "sp") ("stopinsert", "stopi") ("substitute", "s") ("smagic", "sm") ("snomagic", "sno") ("t", "t") ("tabedit", "tabe") ("tabfirst", "tabfir") ("tablast", "tabl") ("tabnew", "tabnew") ("tabnext", "tabn") ("tabNext", "tabN") ("tabonly", "tabo") ("tabprevious", "tabp") ("tabrewind", "tabr") ("undo", "u") ("unlet", "unl") ("vglobal", "v") ("version", "ve") ("vscmd", "vsc") ("vsplit", "vs") ("wqall", "wqa") ("write","w") ("wq", "") ("wall", "wa") ("xall", "xa") ("xit", "x") ("yank", "y") ("/", "") ("?", "") ("<", "") (">", "") ("&", "") ("~", "") ("#", "") ("mapclear", "mapc") ("nmapclear", "nmapc") ("vmapclear", "vmapc") ("xmapclear", "xmapc") ("smapclear", "smapc") ("omapclear", "omapc") ("imapclear", "imapc") ("cmapclear", "cmapc") ("unmap", "unm") ("nunmap", "nun") ("vunmap", "vu") ("xunmap", "xu") ("sunmap", "sunm") ("ounmap", "ou") ("iunmap", "iu") ("lunmap", "lu") ("cunmap", "cu") ("map", "") ("nmap", "nm") ("vmap", "vm") ("xmap", "xm") ("smap", "") ("omap", "om") ("imap", "im") ("lmap", "lm") ("cmap", "cm") ("noremap", "no") ("nnoremap", "nn") ("vnoremap", "vn") ("xnoremap", "xn") ("snoremap", "snor") ("onoremap", "ono") ("inoremap", "ino") ("lnoremap", "ln") ("cnoremap", "cno") ("cwindow", "cw") ("cfirst", "cfir") ("clast", "cla") ("cnext", "cn") ("cNext", "cN") ("cprevious", "cp") ("crewind", "cr") ("lwindow", "lw") ("lfirst", "lfir") ("llast", "lla") ("lnext", "lne") ("lprevious", "lp") ("lNext", "lN") ("lrewind", "lr") ("vimgrep", "vim") ("lvimgrep", "lv") ("abbreviate", "ab") ("iabbrev", "ia") ("cabbrev", "ca") ("noreabbrev", "norea") ("cnoreabbrev", "cnorea") ("inoreabbrev", "inorea") ("abclear", "abc") ("iabclear", "iabc") ("cabclear", "cabc") ("unabbreviate", "una") ("iunabbrev", "iuna") ("cunabbrev", "cuna") ] /// Map of all autocmd events to the lower case version of the name static let s_NameToEventKindMap = [ ("bufnewfile", EventKind.BufNewFile) ("bufreadpre", EventKind.BufReadPre) ("bufread", EventKind.BufRead) ("bufreadpost", EventKind.BufReadPost) ("bufreadcmd", EventKind.BufReadCmd) ("filereadpre", EventKind.FileReadPre) ("filereadpost", EventKind.FileReadPost) ("filereadcmd", EventKind.FileReadCmd) ("filterreadpre", EventKind.FilterReadPre) ("filterreadpost", EventKind.FilterReadPost) ("stdinreadpre", EventKind.StdinReadPre) ("stdinreadpost", EventKind.StdinReadPost) ("bufwrite", EventKind.BufWrite) ("bufwritepre", EventKind.BufWritePre) ("bufwritepost", EventKind.BufWritePost) ("bufwritecmd", EventKind.BufWriteCmd) ("filewritepre", EventKind.FileWritePre) ("filewritepost", EventKind.FileWritePost) ("filewritecmd", EventKind.FileWriteCmd) ("fileappendpre", EventKind.FileAppendPre) ("fileappendpost", EventKind.FileAppendPost) ("fileappendcmd", EventKind.FileAppendCmd) ("filterwritepre", EventKind.FilterWritePre) ("filterwritepost", EventKind.FilterWritePost) ("bufadd", EventKind.BufAdd) ("bufcreate", EventKind.BufCreate) ("bufdelete", EventKind.BufDelete) ("bufwipeout", EventKind.BufWipeout) ("buffilepre", EventKind.BufFilePre) ("buffilepost", EventKind.BufFilePost) ("bufenter", EventKind.BufEnter) ("bufleave", EventKind.BufLeave) ("bufwinenter", EventKind.BufWinEnter) ("bufwinleave", EventKind.BufWinLeave) ("bufunload", EventKind.BufUnload) ("bufhidden", EventKind.BufHidden) ("bufnew", EventKind.BufNew) ("swapexists", EventKind.SwapExists) ("filetype", EventKind.FileType) ("syntax", EventKind.Syntax) ("encodingchanged", EventKind.EncodingChanged) ("termchanged", EventKind.TermChanged) ("vimenter", EventKind.VimEnter) ("guienter", EventKind.GUIEnter) ("termresponse", EventKind.TermResponse) ("vimleavepre", EventKind.VimLeavePre) ("vimleave", EventKind.VimLeave) ("filechangedshell", EventKind.FileChangedShell) ("filechangedshellpost", EventKind.FileChangedShellPost) ("filechangedro", EventKind.FileChangedRO) ("shellcmdpost", EventKind.ShellCmdPost) ("shellfilterpost", EventKind.ShellFilterPost) ("funcundefined", EventKind.FuncUndefined) ("spellfilemissing", EventKind.SpellFileMissing) ("sourcepre", EventKind.SourcePre) ("sourcecmd", EventKind.SourceCmd) ("vimresized", EventKind.VimResized) ("focusgained", EventKind.FocusGained) ("focuslost", EventKind.FocusLost) ("cursorhold", EventKind.CursorHold) ("cursorholdi", EventKind.CursorHoldI) ("cursormoved", EventKind.CursorMoved) ("cursormovedi", EventKind.CursorMovedI) ("winenter", EventKind.WinEnter) ("winleave", EventKind.WinLeave) ("tabenter", EventKind.TabEnter) ("tableave", EventKind.TabLeave) ("cmdwinenter", EventKind.CmdwinEnter) ("cmdwinleave", EventKind.CmdwinLeave) ("insertenter", EventKind.InsertEnter) ("insertchange", EventKind.InsertChange) ("insertleave", EventKind.InsertLeave) ("colorscheme", EventKind.ColorScheme) ("remotereply", EventKind.RemoteReply) ("quickfixcmdpre", EventKind.QuickFixCmdPre) ("quickfixcmdpost", EventKind.QuickFixCmdPost) ("sessionloadpost", EventKind.SessionLoadPost) ("menupopup", EventKind.MenuPopup) ("user", EventKind.User) ] |> Map.ofList new (globalSettings, vimData, lines) as this = Parser(globalSettings, vimData) then this.Reset lines member x.IsDone = _tokenizer.IsAtEndOfLine && _lineIndex + 1 >= _lines.Length member x.ContextLineNumber = _lineIndex /// Parse out the token stream so long as it matches the input. If everything matches /// the tokens will be consumed and 'true' will be returned. Else 'false' will be /// returned and the token stream will be unchanged member x.ParseTokenSequence texts = let mark = _tokenizer.Mark let mutable all = true for text in texts do if _tokenizer.CurrentToken.TokenText = text then _tokenizer.MoveNextToken() else all <- false if not all then _tokenizer.MoveToMark mark all member x.ParseScriptLocalPrefix() = x.ParseTokenSequence [| "<"; "SID"; ">" |] || x.ParseTokenSequence [| "s"; ":" |] /// Reset the parser to the given set of input lines. member x.Reset (lines: string[]) = _lines <- if lines.Length = 0 then [|""|] else lines _lineIndex <- 0 _tokenizer.Reset _lines.[0] TokenizerFlags.None // It's possible the first line of the new input is blank. Need to move past that and settle on // a real line to be processed if x.IsCurrentLineBlank() then x.MoveToNextLine() |> ignore /// Is the current line blank member x.IsCurrentLineBlank() = let mark = _tokenizer.Mark let mutable allBlank = true while not _tokenizer.IsAtEndOfLine && allBlank do if _tokenizer.CurrentTokenKind = TokenKind.Blank then _tokenizer.MoveNextToken() else allBlank <- false _tokenizer.MoveToMark mark allBlank /// Parse the remainder of the line as a file path. If there is nothing else on the line /// then None will be returned member x.ParseRestOfLineAsFilePath() = x.SkipBlanks() if _tokenizer.IsAtEndOfLine then [] else x.ParseRestOfLine() |> x.ParseDirectoryPath /// Move to the next line of the input. This will move past blank lines and return true if /// the result is a non-blank line which can be processed member x.MoveToNextLine() = let doMove () = if _lineIndex + 1 >= _lines.Length then // If this is the last line we should at least move the tokenizer to the end // of the line _tokenizer.MoveToEndOfLine() else _lineIndex <- _lineIndex + 1 _tokenizer.Reset _lines.[_lineIndex] TokenizerFlags.None // Move at least one line doMove () // Now move through all of the blank lines which could appear on the next line while not x.IsDone && x.IsCurrentLineBlank() do doMove () not x.IsDone member x.Tokenizer = _tokenizer /// Move past the white space in the expression text member x.SkipBlanks () = match _tokenizer.CurrentTokenKind with | TokenKind.Blank -> _tokenizer.MoveNextToken() | _ -> () /// Try and expand the possible abbreviation to a full line command name. If it's /// not an abbreviation then the original string will be returned - member x.TryExpand name = + member x.TryExpandCommandName name = // Is 'name' an abbreviation of the given command name and abbreviation let isAbbreviation (fullName: string) (abbreviation: string) = if name = fullName then true else name.StartsWith(abbreviation) && fullName.StartsWith(name) s_LineCommandNamePair |> Seq.filter (fun (name, abbreviation) -> isAbbreviation name abbreviation) |> Seq.map fst |> Seq.tryHead /// Parse out the '!'. Returns true if a ! was found and consumed /// actually skipped member x.ParseBang () = if _tokenizer.CurrentChar = '!' then _tokenizer.MoveNextToken() true else false /// Parse out the text until the given predicate returns false or the end /// of the line is reached. None is return if the current token when /// called doesn't match the predicate member x.ParseWhileEx flags predicate = use reset = _tokenizer.SetTokenizerFlagsScoped flags x.ParseWhile predicate member x.ParseWhile predicate = let builder = System.Text.StringBuilder() let rec inner () = let token = _tokenizer.CurrentToken if token.TokenKind = TokenKind.EndOfLine then () elif predicate token then builder.AppendString token.TokenText _tokenizer.MoveNextToken() inner () else () inner () if builder.Length = 0 then None else builder.ToString() |> Some member x.ParseNumber() = match _tokenizer.CurrentTokenKind with | TokenKind.Number number -> _tokenizer.MoveNextToken() Some number | _ -> None member x.ParseLineRangeSpecifierEndCount lineRange = match x.ParseNumber() with | Some count -> LineRangeSpecifier.WithEndCount (lineRange, count) | None -> lineRange /// Parse out a key notation argument. Different than a word because it can accept items /// which are not letters such as numbers, <, >, etc ... member x.ParseKeyNotation() = x.ParseWhileEx TokenizerFlags.AllowDoubleQuote (fun token -> match token.TokenKind with | TokenKind.Blank -> false | _ -> true) /// Parse out the remainder of the line including any trailing blanks member x.ParseRestOfLine() = match x.ParseWhile (fun _ -> true) with | None -> StringUtil.Empty | Some text -> text /// Create a line number annotated parse error member x.ParseError message = if _lines.Length <> 1 then let lineMessage = _lineIndex + 1 |> Resources.Parser_OnLine sprintf "%s: %s" lineMessage message else message |> LineCommand.ParseError /// Parse out the mapclear variants. member x.ParseMapClear allowBang keyRemapModes = let hasBang = x.ParseBang() x.SkipBlanks() let mapArgumentList = x.ParseMapArguments() if hasBang then if allowBang then LineCommand.ClearKeyMap ([KeyRemapMode.Insert; KeyRemapMode.Command], mapArgumentList) else x.ParseError Resources.Parser_NoBangAllowed else LineCommand.ClearKeyMap (keyRemapModes, mapArgumentList) /// Parse out a number from the stream member x.ParseNumberConstant() = match _tokenizer.CurrentTokenKind with | TokenKind.Number number -> _tokenizer.MoveNextToken() number |> VariableValue.Number |> Expression.ConstantValue |> ParseResult.Succeeded | _ -> ParseResult.Failed "Invalid Number" /// Parse out core portion of key mappings. member x.ParseMappingCore displayFunc mapFunc = x.SkipBlanks() match x.ParseKeyNotation() with | None -> displayFunc None | Some leftKeyNotation -> x.SkipBlanks() let rightKeyNotation = x.ParseWhileEx TokenizerFlags.AllowDoubleQuote (fun _ -> true) let rightKeyNotation = OptionUtil.getOrDefault "" rightKeyNotation if StringUtil.IsBlanks rightKeyNotation then displayFunc (Some leftKeyNotation) else mapFunc leftKeyNotation rightKeyNotation /// Looks for the <buffer> argument that is common to abbreviate commands. Returns true, and consumes /// if it is found. Otherwise it returns false and the tokenizer state remains unchanged member x.ParseAbbreviateBufferArgument() = let mark = _tokenizer.Mark let noBuffer() = _tokenizer.MoveToMark mark false x.SkipBlanks() match _tokenizer.CurrentTokenKind with | TokenKind.Character '<' -> _tokenizer.MoveNextToken() match _tokenizer.CurrentTokenKind with | TokenKind.Word "buffer" -> _tokenizer.MoveNextToken() match _tokenizer.CurrentTokenKind with | TokenKind.Character '>' -> _tokenizer.MoveNextToken() true | _ -> noBuffer() | _ -> noBuffer() | _ -> noBuffer() /// Parse out :abbreviate and all of the mode specific variants member x.ParseAbbreviate(abbreviationModes, allowRemap) = let isLocal = x.ParseAbbreviateBufferArgument() x.ParseMappingCore (fun n -> LineCommand.DisplayAbbreviation (abbreviationModes, n)) (fun l r -> LineCommand.Abbreviate(l, r, allowRemap, abbreviationModes, isLocal)) /// Parse out :abclear member x.ParseAbbreviateClear abbreviationModes = let isLocal = x.ParseAbbreviateBufferArgument() LineCommand.AbbreviateClear (abbreviationModes, isLocal) /// Parse out :unabbreviate and the mode specific variants: cunabbrev and iunabbrev member x.ParseUnabbreviate(abbreviationModes) = let isLocal = x.ParseAbbreviateBufferArgument() x.SkipBlanks() match x.ParseKeyNotation() with | Some keyNotation -> LineCommand.Unabbreviate(keyNotation, abbreviationModes, isLocal) | None -> x.ParseError Resources.Parser_InvalidArgument /// Parse out core portion of key mappings. member x.ParseMapKeysCore keyRemapModes allowRemap = x.SkipBlanks() let mapArgumentList = x.ParseMapArguments() x.ParseMappingCore (fun n -> LineCommand.DisplayKeyMap (keyRemapModes, n)) (fun l r -> LineCommand.MapKeys(l, r, keyRemapModes, allowRemap, mapArgumentList)) /// Parse out the :map commands and all of it's variants (imap, cmap, etc ...) member x.ParseMapKeys allowBang keyRemapModes = if x.ParseBang() then if allowBang then x.ParseMapKeysCore [KeyRemapMode.Insert; KeyRemapMode.Command] true else x.ParseError Resources.Parser_NoBangAllowed else x.ParseMapKeysCore keyRemapModes true /// Parse out the :nomap commands member x.ParseMapKeysNoRemap allowBang keyRemapModes = if x.ParseBang() then if allowBang then x.ParseMapKeysCore [KeyRemapMode.Insert; KeyRemapMode.Command] false else x.ParseError Resources.Parser_NoBangAllowed else x.ParseMapKeysCore keyRemapModes false /// Parse out the unmap variants. member x.ParseMapUnmap allowBang keyRemapModes = let inner modes = x.SkipBlanks() let mapArgumentList = x.ParseMapArguments() match x.ParseKeyNotation() with | None -> x.ParseError Resources.Parser_InvalidArgument | Some keyNotation -> LineCommand.UnmapKeys (keyNotation, modes, mapArgumentList) if x.ParseBang() then if allowBang then inner [KeyRemapMode.Insert; KeyRemapMode.Command] else x.ParseError Resources.Parser_NoBangAllowed else inner keyRemapModes /// Parse out a CommandOption value if the caret is currently pointed at one. If /// there is no CommnadOption here then the index will not change member x.ParseCommandOption () = match _tokenizer.CurrentTokenKind with | TokenKind.Character '+' -> let mark = _tokenizer.Mark _tokenizer.MoveNextToken() match _tokenizer.CurrentTokenKind with | TokenKind.Number number -> _tokenizer.MoveNextToken() CommandOption.StartAtLine number |> Some | TokenKind.Character '/' -> _tokenizer.MoveNextToken() let pattern = x.ParseRestOfLine() CommandOption.StartAtPattern pattern |> Some | TokenKind.Character c -> match x.ParseSingleLine() with | LineCommand.ParseError _ -> _tokenizer.MoveToMark mark None | lineCommand -> CommandOption.ExecuteLineCommand lineCommand |> Some | _ -> // At the end of the line so it's just a '+' option CommandOption.StartAtLastLine |> Some | _ -> None /// Parse out the '++opt' parameter to some commands. member x.ParseFileOptions (): FileOption list = // TODO: Need to implement parsing out FileOption list List.empty /// Parse out the arguments which can be applied to the various map commands. If the /// argument isn't there then the index into the line will remain unchanged member x.ParseMapArguments() = let rec inner withResult = let mark = _tokenizer.Mark // Finish without changing anything. let finish() = _tokenizer.MoveToMark mark withResult [] // The argument is mostly parsed out. Need the closing '>' and the jump to // the next element in the list let completeArgument mapArgument = _tokenizer.MoveNextToken() match _tokenizer.CurrentTokenKind with | TokenKind.Character '>' -> // Skip the '>' and any trailing blanks. The method was called with // the index pointing past white space and it should end that way _tokenizer.MoveNextToken() x.SkipBlanks() inner (fun tail -> withResult (mapArgument :: tail)) | _ -> finish () match _tokenizer.CurrentTokenKind with | TokenKind.Character '<' -> _tokenizer.MoveNextToken() match _tokenizer.CurrentTokenKind with | TokenKind.Word "buffer" -> completeArgument KeyMapArgument.Buffer | TokenKind.Word "silent" -> completeArgument KeyMapArgument.Silent | TokenKind.Word "special" -> completeArgument KeyMapArgument.Special | TokenKind.Word "script" -> completeArgument KeyMapArgument.Script | TokenKind.Word "expr" -> completeArgument KeyMapArgument.Expr | TokenKind.Word "unique" -> completeArgument KeyMapArgument.Unique | _ -> finish() | _ -> finish () inner (fun x -> x) /// Parse out a register value from the text. This will not parse out numbered register member x.ParseRegisterName kind = let c = _tokenizer.CurrentChar let isGood = match kind with | ParseRegisterName.All -> true | ParseRegisterName.NoNumbered -> not (CharUtil.IsDigit c) if isGood then let name = RegisterName.OfChar c if Option.isSome name then _tokenizer.MoveNextChar() name else None /// Used to parse out the flags for the sort commands member x.ParseSortFlags () = // Get the string which we are parsing for flags let flagString = x.ParseWhile (fun token -> match token.TokenKind with | TokenKind.Word _ -> true | _ -> false) let flagString = OptionUtil.getOrDefault "" flagString let mutable parseResult: ParseResult<SortFlags> option = None let mutable flags = SortFlags.None let mutable index = 0 while index < flagString.Length && Option.isNone parseResult do match flagString.[index] with | 'i' -> flags <- flags ||| SortFlags.IgnoreCase | 'n' -> flags <- flags ||| SortFlags.Decimal | 'f' -> flags <- flags ||| SortFlags.Float | 'x' -> flags <- flags ||| SortFlags.Hexidecimal | 'o' -> flags <- flags ||| SortFlags.Octal | 'b' -> flags <- flags ||| SortFlags.Binary | 'u' -> flags <- flags ||| SortFlags.Unique | 'r' -> flags <- flags ||| SortFlags.MatchPattern | _ -> // Illegal character in the flags string parseResult <- ParseResult.Failed Resources.CommandMode_TrailingCharacters |> Some index <- index + 1 match parseResult with | None -> ParseResult.Succeeded flags | Some p -> p /// Used to parse out the flags for substitute commands. Will not modify the /// stream if there are no flags member x.ParseSubstituteFlags () = // Get the string which we are parsing for flags let flagString = x.ParseWhile (fun token -> match token.TokenKind with | TokenKind.Character '&' -> true | TokenKind.Character '#' -> true | TokenKind.Word _ -> true | _ -> false) let flagString = OptionUtil.getOrDefault "" flagString let mutable parseResult: ParseResult<SubstituteFlags> option = None let mutable flags = if _globalSettings.GlobalDefault then SubstituteFlags.ReplaceAll else SubstituteFlags.None let mutable index = 0 while index < flagString.Length && Option.isNone parseResult do match flagString.[index] with | 'c' -> flags <- flags ||| SubstituteFlags.Confirm | 'r' -> flags <- flags ||| SubstituteFlags.UsePreviousSearchPattern | 'e' -> flags <- flags ||| SubstituteFlags.SuppressError | 'i' -> flags <- flags ||| SubstituteFlags.IgnoreCase | 'I' -> flags <- flags ||| SubstituteFlags.OrdinalCase | 'n' -> flags <- flags ||| SubstituteFlags.ReportOnly | 'p' -> flags <- flags ||| SubstituteFlags.PrintLast | 'l' -> flags <- flags ||| SubstituteFlags.PrintLastWithList | '#' -> flags <- flags ||| SubstituteFlags.PrintLastWithNumber | 'g' -> // This is a toggle flag that turns the value on / off if Util.IsFlagSet flags SubstituteFlags.ReplaceAll then flags <- flags &&& ~~~SubstituteFlags.ReplaceAll else flags <- flags ||| SubstituteFlags.ReplaceAll | '&' -> // The '&' flag is only legal in the first position. After that // it terminates the flag notation if index = 0 then flags <- flags ||| SubstituteFlags.UsePreviousFlags else parseResult <- ParseResult.Failed Resources.CommandMode_TrailingCharacters |> Some | _ -> // Illegal character in the flags string parseResult <- ParseResult.Failed Resources.CommandMode_TrailingCharacters |> Some index <- index + 1 match parseResult with | None -> ParseResult.Succeeded flags | Some p -> p /// Used to parse out the flags for the vimgrep commands member x.ParseVimGrepFlags () = // Get the string which we are parsing for flags let flagString = x.ParseWhile (fun token -> match token.TokenKind with | TokenKind.Word _ -> true | _ -> false) let flagString = OptionUtil.getOrDefault "" flagString let mutable parseResult: ParseResult<VimGrepFlags> option = None let mutable flags = VimGrepFlags.None let mutable index = 0 while index < flagString.Length && Option.isNone parseResult do match flagString.[index] with | 'g' -> flags <- flags ||| VimGrepFlags.AllMatchesPerFile | 'j' -> flags <- flags ||| VimGrepFlags.NoJumpToFirst | _ -> // Illegal character in the flags string parseResult <- ParseResult.Failed Resources.CommandMode_TrailingCharacters |> Some index <- index + 1 match parseResult with | None -> ParseResult.Succeeded flags | Some p -> p /// Parse out an '@' command member x.ParseAtCommand lineRange = x.SkipBlanks() if _tokenizer.CurrentChar = ':' then _tokenizer.MoveNextChar() match _vimData.LastLineCommand with | None -> x.ParseError "Error" | Some lineCommand -> x.MergeLineRangeWithCommand lineRange lineCommand else x.ParseError "Error" /// Merge new line range with previous line command member x.MergeLineRangeWithCommand lineRange lineCommand = let noRangeCommand = match lineRange with | LineRangeSpecifier.None -> lineCommand | _ -> x.ParseError "Error" match lineRange with | LineRangeSpecifier.None -> lineCommand | _ -> match lineCommand with | LineCommand.Abbreviate _ -> noRangeCommand | LineCommand.AbbreviateClear _ -> noRangeCommand | LineCommand.AddAutoCommand _ -> noRangeCommand | LineCommand.Behave _ -> noRangeCommand | LineCommand.Call _ -> noRangeCommand | LineCommand.ChangeDirectory _ -> noRangeCommand | LineCommand.ChangeLocalDirectory _ -> noRangeCommand | LineCommand.ClearKeyMap _ -> noRangeCommand | LineCommand.Close _ -> noRangeCommand | LineCommand.Compose _ -> noRangeCommand | LineCommand.CopyTo (_, destLineRange, count) -> LineCommand.CopyTo (lineRange, destLineRange, count) | LineCommand.CSharpScript _ -> noRangeCommand | LineCommand.CSharpScriptCreateEachTime _ -> noRangeCommand | LineCommand.Delete (_, registerName) -> LineCommand.Delete (lineRange, registerName) | LineCommand.DeleteAllMarks -> noRangeCommand | LineCommand.DeleteMarks _ -> noRangeCommand | LineCommand.Digraphs _ -> noRangeCommand | LineCommand.DisplayAbbreviation _ -> noRangeCommand | LineCommand.DisplayKeyMap _ -> noRangeCommand | LineCommand.DisplayLet _ -> noRangeCommand | LineCommand.DisplayMarks _ -> noRangeCommand | LineCommand.DisplayRegisters _ -> noRangeCommand | LineCommand.Echo _ -> noRangeCommand | LineCommand.Edit _ -> noRangeCommand | LineCommand.Else -> noRangeCommand | LineCommand.ElseIf _ -> noRangeCommand | LineCommand.Execute _ -> noRangeCommand | LineCommand.Files -> noRangeCommand | LineCommand.Fold lineRange -> LineCommand.Fold lineRange | LineCommand.Function _ -> noRangeCommand | LineCommand.FunctionEnd _ -> noRangeCommand | LineCommand.FunctionStart _ -> noRangeCommand | LineCommand.Global (_, pattern, matchPattern, lineCommand) -> LineCommand.Global (lineRange, pattern, matchPattern, lineCommand) | LineCommand.GoToFirstTab -> noRangeCommand | LineCommand.GoToLastTab -> noRangeCommand | LineCommand.GoToNextTab _ -> noRangeCommand | LineCommand.GoToPreviousTab _ -> noRangeCommand | LineCommand.Help _ -> noRangeCommand | LineCommand.History -> noRangeCommand | LineCommand.HorizontalSplit (_, fileOptions, commandOptions) -> LineCommand.HorizontalSplit (lineRange, fileOptions, commandOptions) | LineCommand.HostCommand _ -> noRangeCommand | LineCommand.If _ -> noRangeCommand | LineCommand.IfEnd -> noRangeCommand | LineCommand.IfStart _ -> noRangeCommand | LineCommand.Join (_, joinKind) -> LineCommand.Join (lineRange, joinKind) | LineCommand.JumpToLastLine _ -> LineCommand.JumpToLastLine lineRange | LineCommand.Let _ -> noRangeCommand | LineCommand.LetEnvironment _ -> noRangeCommand | LineCommand.LetRegister _ -> noRangeCommand | LineCommand.Make _ -> noRangeCommand | LineCommand.MapKeys _ -> noRangeCommand | LineCommand.MoveTo (_, destLineRange, count) -> LineCommand.MoveTo (lineRange, destLineRange, count) | LineCommand.NavigateToListItem _ -> noRangeCommand | LineCommand.NoHighlightSearch -> noRangeCommand | LineCommand.Nop -> noRangeCommand | LineCommand.Normal (_, command) -> LineCommand.Normal (lineRange, command) | LineCommand.Only -> noRangeCommand | LineCommand.OpenListWindow _ -> noRangeCommand | LineCommand.ParseError _ -> noRangeCommand | LineCommand.DisplayLines (_, lineCommandFlags)-> LineCommand.DisplayLines (lineRange, lineCommandFlags) | LineCommand.PrintCurrentDirectory -> noRangeCommand | LineCommand.PutAfter (_, registerName) -> LineCommand.PutAfter (lineRange, registerName) | LineCommand.PutBefore (_, registerName) -> LineCommand.PutBefore (lineRange, registerName) | LineCommand.Quit _ -> noRangeCommand | LineCommand.QuitAll _ -> noRangeCommand | LineCommand.QuitWithWrite (_, hasBang, fileOptions, filePath) -> LineCommand.QuitWithWrite (lineRange, hasBang, fileOptions, filePath) | LineCommand.ReadCommand (_, command) -> LineCommand.ReadCommand (lineRange, command) | LineCommand.ReadFile (_, fileOptionList, filePath) -> LineCommand.ReadFile (lineRange, fileOptionList, filePath) | LineCommand.Redo -> noRangeCommand | LineCommand.RemoveAutoCommands _ -> noRangeCommand | LineCommand.Retab (_, hasBang, tabStop) -> LineCommand.Retab (lineRange, hasBang, tabStop) | LineCommand.Search (_, path, pattern) -> LineCommand.Search (lineRange, path, pattern) | LineCommand.Set _ -> noRangeCommand | LineCommand.Shell -> noRangeCommand | LineCommand.ShellCommand (_, command) -> LineCommand.ShellCommand (lineRange, command) | LineCommand.ShiftLeft (_, count) -> LineCommand.ShiftLeft (lineRange, count) | LineCommand.ShiftRight (_, count) -> LineCommand.ShiftRight (lineRange, count) | LineCommand.Sort (_, hasBang, flags, pattern) -> LineCommand.Sort (lineRange, hasBang, flags, pattern) | LineCommand.Source _ -> noRangeCommand | LineCommand.StopInsert -> noRangeCommand | LineCommand.Substitute (_, pattern, replace, flags) -> LineCommand.Substitute (lineRange, pattern, replace, flags) @@ -2235,835 +2235,835 @@ and [<Sealed>] internal Parser | ParseResult.Succeeded (Expression.RegisterName registerName) -> parseAssignment registerName (fun lhs rhs -> LineCommand.LetRegister (lhs, rhs)) | ParseResult.Failed msg -> x.ParseError msg | _ -> x.ParseError Resources.Parser_Error /// Parse out the :make command. The arguments here other than ! are undefined. Just /// get the text blob and let the interpreter / host deal with it member x.ParseMake () = let hasBang = x.ParseBang() x.SkipBlanks() let arguments = x.ParseRestOfLine() LineCommand.Make (hasBang, arguments) /// Parse out the :put command. The presence of a bang indicates that we need /// to put before instead of after member x.ParsePut lineRange = let hasBang = x.ParseBang() x.SkipBlanks() let registerName = x.ParseRegisterName ParseRegisterName.NoNumbered if hasBang then LineCommand.PutBefore (lineRange, registerName) else LineCommand.PutAfter (lineRange, registerName) member x.ParseDisplayLines lineRange initialFlags = x.SkipBlanks() let lineRange = x.ParseLineRangeSpecifierEndCount lineRange x.SkipBlanks() _lineCommandBuilder { let! flags = x.ParseLineCommandFlags initialFlags return LineCommand.DisplayLines (lineRange, flags) } /// Parse out the :read command member x.ParseRead lineRange = x.SkipBlanks() let fileOptionList = x.ParseFileOptions() match fileOptionList with | [] -> // Can still be the file or command variety. The ! or lack there of will // differentiate it at this point x.SkipBlanks() if _tokenizer.CurrentChar = '!' then _tokenizer.MoveNextToken() use resetFlags = _tokenizer.SetTokenizerFlagsScoped TokenizerFlags.AllowDoubleQuote let command = x.ParseRestOfLine() LineCommand.ReadCommand (lineRange, command) else let filePath = x.ParseRestOfLine() LineCommand.ReadFile (lineRange, [], filePath) | _ -> // Can only be the file variety. x.SkipBlanks() let filePath = x.ParseRestOfLine() LineCommand.ReadFile (lineRange, fileOptionList, filePath) /// Parse out the :retab command member x.ParseRetab lineRange = let hasBang = x.ParseBang() x.SkipBlanks() let newTabStop = x.ParseNumber() LineCommand.Retab (lineRange, hasBang, newTabStop) /// Whether the specified setting is a file name setting, e.g. shell /// TODO: A local setting might someday be a file name setting member x.IsFileNameSetting (name: string) = match _globalSettings.GetSetting name with | None -> false | Some setting -> setting.HasFileNameOption /// Parse out the :set command and all of it's variants member x.ParseSet () = // Parse out an individual option and add it to the 'withArgument' continuation let rec parseOption withArgument = x.SkipBlanks() // Parse out the next argument and use 'argument' as the value of the current // argument let parseNext argument = parseOption (fun list -> argument :: list |> withArgument) // Parse out an operator. Parse out the value and use the specified setting name // and argument function as the argument let parseSetValue name argumentFunc = if _tokenizer.IsAtEndOfLine || _tokenizer.CurrentChar = ' ' then _tokenizer.MoveNextToken() parseNext (SetArgument.AssignSetting (name, "")) else let isFileName = x.IsFileNameSetting name let value = x.ParseOptionBackslash isFileName parseNext (argumentFunc (name, value)) // Parse out a simple assignment. Move past the assignment char and get the value let parseAssign name = _tokenizer.MoveNextChar() parseSetValue name SetArgument.AssignSetting // Parse out a compound operator. This is used for '+=' and such. This will be called // with the index pointed at the first character let parseCompoundOperator name argumentFunc = _tokenizer.MoveNextToken() if _tokenizer.CurrentChar = '=' then _tokenizer.MoveNextChar() parseSetValue name argumentFunc else x.ParseError Resources.Parser_Error match _tokenizer.CurrentTokenKind with | TokenKind.EndOfLine -> let list = withArgument [] LineCommand.Set list | TokenKind.Word "all" -> _tokenizer.MoveNextToken() if _tokenizer.CurrentChar = '&' then _tokenizer.MoveNextToken() parseNext SetArgument.ResetAllToDefault else parseNext SetArgument.DisplayAllButTerminal | TokenKind.Word "termcap" -> _tokenizer.MoveNextToken() parseNext SetArgument.DisplayAllTerminal | TokenKind.Word name -> // An option name can have an '_' due to the vsvim extension names let name = x.ParseWhile (fun token -> match token.TokenKind with | TokenKind.Word _ -> true | TokenKind.Character '_' -> true | _ -> false) |> OptionUtil.getOrDefault "" if name.StartsWith("no", System.StringComparison.Ordinal) then let option = name.Substring(2) parseNext (SetArgument.ToggleOffSetting option) elif name.StartsWith("inv", System.StringComparison.Ordinal) then let option = name.Substring(3) parseNext (SetArgument.InvertSetting option) else // Need to look at the next character to decide what type of // argument this is match _tokenizer.CurrentTokenKind with | TokenKind.Character '?' -> _tokenizer.MoveNextToken(); parseNext (SetArgument.DisplaySetting name) | TokenKind.Character '!' -> _tokenizer.MoveNextToken(); parseNext (SetArgument.InvertSetting name) | TokenKind.Character ':' -> parseAssign name | TokenKind.Character '=' -> parseAssign name | TokenKind.Character '+' -> parseCompoundOperator name SetArgument.AddSetting | TokenKind.Character '^' -> parseCompoundOperator name SetArgument.MultiplySetting | TokenKind.Character '-' -> parseCompoundOperator name SetArgument.SubtractSetting | TokenKind.Blank -> _tokenizer.MoveNextToken(); parseNext (SetArgument.UseSetting name) | TokenKind.EndOfLine -> parseNext (SetArgument.UseSetting name) | _ -> x.ParseError Resources.Parser_Error | _ -> x.ParseError Resources.Parser_Error parseOption (fun x -> x) /// Parse out the :sort command member x.ParseSort lineRange = // Whether this valid as a sort string delimiter let isValidDelimiter c = let isBad = CharUtil.IsLetter c not isBad let hasBang = x.ParseBang() x.SkipBlanks() match x.ParseSortFlags() with | ParseResult.Failed message -> x.ParseError message | ParseResult.Succeeded flags -> x.SkipBlanks() match _tokenizer.CurrentTokenKind with | TokenKind.Character delimiter -> if isValidDelimiter delimiter then _tokenizer.MoveNextToken() let pattern, foundDelimiter = x.ParsePattern delimiter if not foundDelimiter then LineCommand.Sort (lineRange, hasBang, flags, Some pattern) else x.SkipBlanks() match x.ParseSortFlags() with | ParseResult.Failed message -> x.ParseError message | ParseResult.Succeeded moreFlags -> let flags = flags ||| moreFlags LineCommand.Sort (lineRange, hasBang, flags, Some pattern) else LineCommand.Sort (lineRange, hasBang, flags, None) | _ -> LineCommand.Sort (lineRange, hasBang, flags, None) /// Parse out the :source command. It can have an optional '!' following it then a file /// name member x.ParseSource() = let hasBang = x.ParseBang() x.SkipBlanks() let fileName = x.ParseRestOfLine() let fileName = fileName.Trim() LineCommand.Source (hasBang, fileName) /// Parse out the :split command member x.ParseSplit splitType lineRange = x.SkipBlanks() let fileOptionList = x.ParseFileOptions() x.SkipBlanks() let commandOption = x.ParseCommandOption() splitType (lineRange, fileOptionList, commandOption) member x.ParseStopInsert () = LineCommand.StopInsert /// Parse out the :qal and :quitall commands member x.ParseQuitAll () = let hasBang = x.ParseBang() LineCommand.QuitAll hasBang /// Parse out the :quit command. member x.ParseQuit () = let hasBang = x.ParseBang() LineCommand.Quit hasBang /// Parse out the ':digraphs' command member x.ParseDigraphs () = let mutable digraphList: (char * char * int) list = List.Empty let mutable (result: LineCommand option) = None let mutable more = true while more do x.SkipBlanks() if _tokenizer.IsAtEndOfLine then more <- false else let char1 = _tokenizer.CurrentChar _tokenizer.MoveNextChar() if _tokenizer.IsAtEndOfLine then result <- x.ParseError Resources.CommandMode_InvalidCommand |> Some else let char2 = _tokenizer.CurrentChar _tokenizer.MoveNextChar() x.SkipBlanks() match x.ParseNumber() with | Some number -> let digraph = (char1, char2, number) digraphList <- digraph :: digraphList | None -> result <- x.ParseError Resources.CommandMode_InvalidCommand |> Some match result with | Some lineCommand -> lineCommand | None -> digraphList <- List.rev digraphList LineCommand.Digraphs digraphList /// Parse out the :display and :registers command. Just takes a single argument /// which is the register name member x.ParseDisplayRegisters () = let mutable nameList: RegisterName list = List.Empty let mutable more = true while more do x.SkipBlanks() match x.ParseRegisterName ParseRegisterName.All with | Some name -> nameList <- name :: nameList more <- true | None -> more <- false nameList <- List.rev nameList LineCommand.DisplayRegisters nameList /// Parse out the :marks command. Handles both the no argument and argument /// case member x.ParseDisplayMarks () = x.SkipBlanks() match _tokenizer.CurrentTokenKind with | TokenKind.Word word -> _tokenizer.MoveNextToken() let mutable message: string option = None let list = System.Collections.Generic.List<Mark>() for c in word do match Mark.OfChar c with | None -> message <- Some (Resources.Parser_NoMarksMatching c) | Some mark -> list.Add(mark) match message with | None -> LineCommand.DisplayMarks (List.ofSeq list) | Some message -> x.ParseError message | _ -> // Simple case. No marks to parse out. Just return them all LineCommand.DisplayMarks List.empty /// Parse a single line. This will not attempt to link related LineCommand values like :function /// and :endfunc. Instead it will return the result of the current LineCommand member x.ParseSingleLine() = // Skip the white space and: at the beginning of the line while _tokenizer.CurrentChar = ':' || _tokenizer.CurrentTokenKind = TokenKind.Blank do _tokenizer.MoveNextChar() let lineRange = x.ParseLineRange() // Skip the white space after a valid line range. match lineRange with | LineRangeSpecifier.None -> () | _ -> x.SkipBlanks() let noRange parseFunc = match lineRange with | LineRangeSpecifier.None -> parseFunc() | _ -> x.ParseError Resources.Parser_NoRangeAllowed let handleParseResult (lineCommand: LineCommand) = let lineCommand = if lineCommand.Failed then // If there is already a failure don't look any deeper. lineCommand else x.SkipBlanks() if _tokenizer.IsAtEndOfLine then lineCommand elif _tokenizer.CurrentChar = '|' then _tokenizer.MoveNextChar() let nextCommand = x.ParseSingleLine() if nextCommand.Failed then nextCommand else LineCommand.Compose (lineCommand, nextCommand) else // If there are still characters then it's illegal // trailing characters. x.ParseError Resources.CommandMode_TrailingCharacters x.MoveToNextLine() |> ignore lineCommand let handleCount parseFunc = match lineRange with | LineRangeSpecifier.SingleLine lineSpecifier -> match lineSpecifier with | LineSpecifier.Number count -> parseFunc (Some count) | _ -> parseFunc None | _ -> parseFunc None let doParse name = let parseResult = match name with | "abbreviate" -> noRange (fun () -> x.ParseAbbreviate(AbbreviationMode.All, allowRemap = true)) | "abclear" -> noRange (fun () -> x.ParseAbbreviateClear AbbreviationMode.All) | "autocmd" -> noRange x.ParseAutoCommand | "behave" -> noRange x.ParseBehave | "buffers" -> noRange x.ParseFiles | "call" -> x.ParseCall lineRange | "cabbrev" -> noRange (fun () -> x.ParseAbbreviate([AbbreviationMode.Command], allowRemap = true)) | "cabclear" -> noRange (fun () -> x.ParseAbbreviateClear [AbbreviationMode.Command]) | "cnoreabbrev" -> noRange (fun () -> x.ParseAbbreviate([AbbreviationMode.Command], allowRemap = false)) | "cd" -> noRange x.ParseChangeDirectory | "cfirst" -> x.ParseNavigateToListItem lineRange ListKind.Error NavigationKind.First | "chdir" -> noRange x.ParseChangeDirectory | "clast" -> x.ParseNavigateToListItem lineRange ListKind.Error NavigationKind.Last | "close" -> noRange x.ParseClose | "cmap"-> noRange (fun () -> x.ParseMapKeys false [KeyRemapMode.Command]) | "cmapclear" -> noRange (fun () -> x.ParseMapClear false [KeyRemapMode.Command]) | "cnext" -> x.ParseNavigateToListItem lineRange ListKind.Error NavigationKind.Next | "cNext" -> x.ParseNavigateToListItem lineRange ListKind.Error NavigationKind.Previous | "cnoremap"-> noRange (fun () -> x.ParseMapKeysNoRemap false [KeyRemapMode.Command]) | "copy" -> x.ParseCopyTo lineRange | "cprevious" -> x.ParseNavigateToListItem lineRange ListKind.Error NavigationKind.Previous | "crewind" -> x.ParseNavigateToListItem lineRange ListKind.Error NavigationKind.First | "csx" -> x.ParseCSharpScript(lineRange, createEachTime = false) | "csxe" -> x.ParseCSharpScript(lineRange, createEachTime = true) | "cunmap" -> noRange (fun () -> x.ParseMapUnmap false [KeyRemapMode.Command]) | "cunabbrev" -> noRange (fun () -> x.ParseUnabbreviate [AbbreviationMode.Command]) | "cwindow" -> noRange (fun () -> x.ParseOpenListWindow ListKind.Error) | "delete" -> x.ParseDelete lineRange | "delmarks" -> noRange (fun () -> x.ParseDeleteMarks()) | "digraphs" -> noRange x.ParseDigraphs | "display" -> noRange x.ParseDisplayRegisters | "echo" -> noRange x.ParseEcho | "edit" -> noRange x.ParseEdit | "else" -> noRange x.ParseElse | "execute" -> noRange x.ParseExecute | "elseif" -> noRange x.ParseElseIf | "endfunction" -> noRange x.ParseFunctionEnd | "endif" -> noRange x.ParseIfEnd | "exit" -> x.ParseQuitAndWrite lineRange | "files" -> noRange x.ParseFiles | "fold" -> x.ParseFold lineRange | "function" -> noRange x.ParseFunctionStart | "global" -> x.ParseGlobal lineRange | "normal" -> x.ParseNormal lineRange | "help" -> noRange x.ParseHelp | "history" -> noRange (fun () -> x.ParseHistory()) | "iabbrev" -> noRange (fun () -> x.ParseAbbreviate([AbbreviationMode.Insert], allowRemap = true)) | "iabclear" -> noRange (fun () -> x.ParseAbbreviateClear [AbbreviationMode.Insert]) | "inoreabbrev" -> noRange (fun () -> x.ParseAbbreviate([AbbreviationMode.Insert], allowRemap = false)) | "iunabbrev" -> noRange (fun () -> x.ParseUnabbreviate [AbbreviationMode.Insert]) | "if" -> noRange x.ParseIfStart | "iunmap" -> noRange (fun () -> x.ParseMapUnmap false [KeyRemapMode.Insert]) | "imap"-> noRange (fun () -> x.ParseMapKeys false [KeyRemapMode.Insert]) | "imapclear" -> noRange (fun () -> x.ParseMapClear false [KeyRemapMode.Insert]) | "inoremap"-> noRange (fun () -> x.ParseMapKeysNoRemap false [KeyRemapMode.Insert]) | "join" -> x.ParseJoin lineRange | "lcd" -> noRange x.ParseChangeLocalDirectory | "lchdir" -> noRange x.ParseChangeLocalDirectory | "let" -> noRange x.ParseLet | "lfirst" -> x.ParseNavigateToListItem lineRange ListKind.Location NavigationKind.First | "list" -> x.ParseDisplayLines lineRange LineCommandFlags.List | "llast" -> x.ParseNavigateToListItem lineRange ListKind.Location NavigationKind.Last | "lmap"-> noRange (fun () -> x.ParseMapKeys false [KeyRemapMode.Language]) | "lnext" -> x.ParseNavigateToListItem lineRange ListKind.Location NavigationKind.Next | "lNext" -> x.ParseNavigateToListItem lineRange ListKind.Location NavigationKind.Previous | "lnoremap"-> noRange (fun () -> x.ParseMapKeysNoRemap false [KeyRemapMode.Language]) | "lprevious" -> x.ParseNavigateToListItem lineRange ListKind.Location NavigationKind.Previous | "lrewind" -> x.ParseNavigateToListItem lineRange ListKind.Location NavigationKind.First | "ls" -> noRange x.ParseFiles | "lunmap" -> noRange (fun () -> x.ParseMapUnmap false [KeyRemapMode.Language]) | "lvimgrep" -> handleCount x.ParseVimGrep | "lwindow" -> noRange (fun () -> x.ParseOpenListWindow ListKind.Location) | "make" -> noRange x.ParseMake | "marks" -> noRange x.ParseDisplayMarks | "map"-> noRange (fun () -> x.ParseMapKeys true [KeyRemapMode.Normal; KeyRemapMode.Visual; KeyRemapMode.Select; KeyRemapMode.OperatorPending]) | "mapclear" -> noRange (fun () -> x.ParseMapClear true [KeyRemapMode.Normal; KeyRemapMode.Visual; KeyRemapMode.Command; KeyRemapMode.OperatorPending]) | "move" -> x.ParseMoveTo lineRange | "nmap"-> noRange (fun () -> x.ParseMapKeys false [KeyRemapMode.Normal]) | "nmapclear" -> noRange (fun () -> x.ParseMapClear false [KeyRemapMode.Normal]) | "nnoremap"-> noRange (fun () -> x.ParseMapKeysNoRemap false [KeyRemapMode.Normal]) | "number" -> x.ParseDisplayLines lineRange LineCommandFlags.AddLineNumber | "nunmap" -> noRange (fun () -> x.ParseMapUnmap false [KeyRemapMode.Normal]) | "nohlsearch" -> noRange (fun () -> LineCommand.NoHighlightSearch) | "noreabbrev " -> noRange (fun () -> x.ParseAbbreviate(AbbreviationMode.All, allowRemap = false)) | "noremap"-> noRange (fun () -> x.ParseMapKeysNoRemap true [KeyRemapMode.Normal; KeyRemapMode.Visual; KeyRemapMode.Select; KeyRemapMode.OperatorPending]) | "omap"-> noRange (fun () -> x.ParseMapKeys false [KeyRemapMode.OperatorPending]) | "omapclear" -> noRange (fun () -> x.ParseMapClear false [KeyRemapMode.OperatorPending]) | "only" -> noRange (fun () -> LineCommand.Only) | "onoremap"-> noRange (fun () -> x.ParseMapKeysNoRemap false [KeyRemapMode.OperatorPending]) | "ounmap" -> noRange (fun () -> x.ParseMapUnmap false [KeyRemapMode.OperatorPending]) | "put" -> x.ParsePut lineRange | "print" -> x.ParseDisplayLines lineRange LineCommandFlags.Print | "pwd" -> noRange (fun () -> LineCommand.PrintCurrentDirectory) | "quit" -> noRange x.ParseQuit | "qall" -> noRange x.ParseQuitAll | "quitall" -> noRange x.ParseQuitAll | "read" -> x.ParseRead lineRange | "redo" -> noRange (fun () -> LineCommand.Redo) | "retab" -> x.ParseRetab lineRange | "registers" -> noRange x.ParseDisplayRegisters | "set" -> noRange x.ParseSet | "shell" -> noRange x.ParseShell | "sort" -> x.ParseSort lineRange | "source" -> noRange x.ParseSource | "split" -> x.ParseSplit LineCommand.HorizontalSplit lineRange | "stopinsert" -> x.ParseStopInsert() | "substitute" -> x.ParseSubstitute lineRange (fun x -> x) | "smagic" -> x.ParseSubstituteMagic lineRange | "smap"-> noRange (fun () -> x.ParseMapKeys false [KeyRemapMode.Select]) | "smapclear" -> noRange (fun () -> x.ParseMapClear false [KeyRemapMode.Select]) | "snomagic" -> x.ParseSubstituteNoMagic lineRange | "snoremap"-> noRange (fun () -> x.ParseMapKeysNoRemap false [KeyRemapMode.Select]) | "sunmap" -> noRange (fun () -> x.ParseMapUnmap false [KeyRemapMode.Select]) | "t" -> x.ParseCopyTo lineRange | "tabedit" -> noRange x.ParseTabNew | "tabfirst" -> noRange (fun () -> LineCommand.GoToFirstTab) | "tabrewind" -> noRange (fun () -> LineCommand.GoToFirstTab) | "tablast" -> noRange (fun () -> LineCommand.GoToLastTab) | "tabnew" -> noRange x.ParseTabNew | "tabnext" -> noRange x.ParseTabNext | "tabNext" -> noRange x.ParseTabPrevious | "tabonly" -> noRange (fun () -> LineCommand.TabOnly) | "tabprevious" -> noRange x.ParseTabPrevious | "unabbreviate" -> noRange (fun () -> x.ParseUnabbreviate AbbreviationMode.All) | "undo" -> noRange (fun () -> LineCommand.Undo) | "unlet" -> noRange x.ParseUnlet | "unmap" -> noRange (fun () -> x.ParseMapUnmap true [KeyRemapMode.Normal; KeyRemapMode.Visual; KeyRemapMode.Select; KeyRemapMode.OperatorPending]) | "version" -> noRange (fun () -> LineCommand.Version) | "vimhelp" -> noRange x.ParseVimHelp | "vimgrep" -> handleCount x.ParseVimGrep | "vglobal" -> x.ParseGlobalCore lineRange false | "vmap"-> noRange (fun () -> x.ParseMapKeys false [KeyRemapMode.Visual; KeyRemapMode.Select]) | "vmapclear" -> noRange (fun () -> x.ParseMapClear false [KeyRemapMode.Visual; KeyRemapMode.Select]) | "vscmd" -> x.ParseHostCommand() | "vsplit" -> x.ParseSplit LineCommand.VerticalSplit lineRange | "vnoremap"-> noRange (fun () -> x.ParseMapKeysNoRemap false [KeyRemapMode.Visual; KeyRemapMode.Select]) | "vunmap" -> noRange (fun () -> x.ParseMapUnmap false [KeyRemapMode.Visual; KeyRemapMode.Select]) | "wall" -> noRange (fun () -> x.ParseWriteAll false) | "wqall" -> noRange (fun () -> x.ParseWriteAll true) | "write" -> x.ParseWrite lineRange | "wq" -> x.ParseQuitAndWrite lineRange | "xall"-> noRange (fun () -> x.ParseWriteAll true) | "xit" -> x.ParseQuitAndWrite lineRange | "xmap"-> noRange (fun () -> x.ParseMapKeys false [KeyRemapMode.Visual]) | "xmapclear" -> noRange (fun () -> x.ParseMapClear false [KeyRemapMode.Visual]) | "xnoremap"-> noRange (fun () -> x.ParseMapKeysNoRemap false [KeyRemapMode.Visual]) | "xunmap" -> noRange (fun () -> x.ParseMapUnmap false [KeyRemapMode.Visual]) | "yank" -> x.ParseYank lineRange | "/" -> x.ParseSearch lineRange SearchPath.Forward | "?" -> x.ParseSearch lineRange SearchPath.Backward | "<" -> x.ParseShiftLeft lineRange | ">" -> x.ParseShiftRight lineRange | "&" -> x.ParseSubstituteRepeat lineRange SubstituteFlags.None | "~" -> x.ParseSubstituteRepeat lineRange SubstituteFlags.UsePreviousSearchPattern | "!" -> x.ParseShellCommand lineRange | "@" -> x.ParseAtCommand lineRange | "#" -> x.ParseDisplayLines lineRange LineCommandFlags.AddLineNumber | _ -> x.ParseError Resources.Parser_Error handleParseResult parseResult let expandOrCurrent name = - match x.TryExpand name with + match x.TryExpandCommandName name with | Some expanded -> expanded | None -> name // Get the command name and make sure to expand it to it's possible // full name. match _tokenizer.CurrentTokenKind with | TokenKind.Word word -> _tokenizer.MoveNextToken() expandOrCurrent word |> doParse | TokenKind.Character c -> _tokenizer.MoveNextToken() c |> StringUtil.OfChar |> expandOrCurrent |> doParse | TokenKind.EndOfLine -> match lineRange with | LineRangeSpecifier.None -> handleParseResult LineCommand.Nop | _ -> LineCommand.JumpToLastLine lineRange |> handleParseResult | _ -> LineCommand.JumpToLastLine lineRange |> handleParseResult /// Parse out a single command. Unlike ParseSingleLine this will parse linked commands. So /// it won't ever return LineCommand.FuntionStart but instead will return LineCommand.Function /// instead member x.ParseSingleCommand() = match x.ParseSingleLine() with | LineCommand.FunctionStart functionDefinition -> x.ParseFunction functionDefinition | LineCommand.IfStart expr -> x.ParseIf expr | lineCommand -> lineCommand // Parse out the name of a setting/option member x.ParseOptionName() = _tokenizer.MoveNextToken() let tokenKind = _tokenizer.CurrentTokenKind _tokenizer.MoveNextToken() match tokenKind with | TokenKind.Word word -> Expression.OptionName word |> ParseResult.Succeeded | _ -> ParseResult.Failed "Option name missing" member x.ParseList() = let rec parseList atBeginning = let recursivelyParseItems() = match x.ParseSingleExpression() with | ParseResult.Succeeded item -> match parseList false with | ParseResult.Succeeded otherItems -> item :: otherItems |> ParseResult.Succeeded | ParseResult.Failed msg -> ParseResult.Failed msg | ParseResult.Failed msg -> ParseResult.Failed msg match _tokenizer.CurrentTokenKind with | TokenKind.Character '[' -> _tokenizer.MoveNextToken() parseList true | TokenKind.Character ']' -> _tokenizer.MoveNextToken() ParseResult.Succeeded [] | TokenKind.Character ',' -> _tokenizer.MoveNextToken() x.SkipBlanks() recursivelyParseItems() | _ -> if atBeginning then recursivelyParseItems() else ParseResult.Failed Resources.Parser_Error match parseList true with | ParseResult.Succeeded expressionList -> Expression.List expressionList |> ParseResult.Succeeded | ParseResult.Failed msg -> ParseResult.Failed msg member x.ParseDictionary() = _tokenizer.MoveNextToken() match _tokenizer.CurrentTokenKind with | TokenKind.Character '}' -> _tokenizer.MoveNextToken() VariableValue.Dictionary Map.empty |> Expression.ConstantValue |> ParseResult.Succeeded | _ -> ParseResult.Failed Resources.Parser_Error /// Parse out a single expression member x.ParseSingleExpression() = // Re-examine the current token based on the knowledge that double quotes are // legal in this context as a real token use reset = _tokenizer.SetTokenizerFlagsScoped TokenizerFlags.AllowDoubleQuote match _tokenizer.CurrentTokenKind with | TokenKind.Character '\"' -> x.ParseStringConstant() | TokenKind.Character '\'' -> x.ParseStringLiteral() | TokenKind.Character '&' -> x.ParseOptionName() | TokenKind.Character '[' -> x.ParseList() | TokenKind.Character '{' -> x.ParseDictionary() | TokenKind.Character '$' -> x.ParseEnvironmentVariableName() | TokenKind.Character '@' -> _tokenizer.MoveNextToken() match x.ParseRegisterName ParseRegisterName.All with | Some name -> Expression.RegisterName name |> ParseResult.Succeeded | None -> ParseResult.Failed Resources.Parser_UnrecognizedRegisterName | TokenKind.Number number -> _tokenizer.MoveNextToken() VariableValue.Number number |> Expression.ConstantValue |> ParseResult.Succeeded | _ -> match x.ParseVariableName() with | ParseResult.Failed msg -> ParseResult.Failed msg | ParseResult.Succeeded variable -> // TODO the nesting is getting deep here; refactor x.SkipBlanks() match _tokenizer.CurrentTokenKind with | TokenKind.Character '(' -> match x.ParseFunctionArguments true with | ParseResult.Succeeded args -> Expression.FunctionCall(variable, args) |> ParseResult.Succeeded | ParseResult.Failed msg -> ParseResult.Failed msg | _ -> Expression.VariableName variable |> ParseResult.Succeeded member x.ParseFunctionArguments atBeginning = let recursivelyParseArguments() = match x.ParseSingleExpression() with | ParseResult.Succeeded arg -> match x.ParseFunctionArguments false with | ParseResult.Succeeded otherArgs -> arg :: otherArgs |> ParseResult.Succeeded | ParseResult.Failed msg -> ParseResult.Failed msg | ParseResult.Failed msg -> ParseResult.Failed msg match _tokenizer.CurrentTokenKind with | TokenKind.Character '(' -> _tokenizer.MoveNextToken() x.ParseFunctionArguments true | TokenKind.Character ')' -> _tokenizer.MoveNextToken() ParseResult.Succeeded [] | TokenKind.Character ',' -> _tokenizer.MoveNextToken() x.SkipBlanks() recursivelyParseArguments() | _ -> if atBeginning then recursivelyParseArguments() else ParseResult.Failed "invalid arguments for function" /// Parse out a complete expression from the text. member x.ParseExpressionCore() = _parseResultBuilder { let! expr = x.ParseSingleExpression() x.SkipBlanks() // Parsee out a binary expression let parseBinary binaryKind = _tokenizer.MoveNextToken() x.SkipBlanks() _parseResultBuilder { let! rightExpr = x.ParseSingleExpression() return Expression.Binary (binaryKind, expr, rightExpr) } match _tokenizer.CurrentTokenKind with | TokenKind.Character '+' -> return! parseBinary BinaryKind.Add | TokenKind.Character '/' -> return! parseBinary BinaryKind.Divide | TokenKind.Character '*' -> return! parseBinary BinaryKind.Multiply | TokenKind.Character '.' -> return! parseBinary BinaryKind.Concatenate | TokenKind.Character '-' -> return! parseBinary BinaryKind.Subtract | TokenKind.Character '%' -> return! parseBinary BinaryKind.Modulo | TokenKind.Character '>' -> return! parseBinary BinaryKind.GreaterThan | TokenKind.Character '<' -> return! parseBinary BinaryKind.LessThan | TokenKind.ComplexOperator "==" -> return! parseBinary BinaryKind.Equal | TokenKind.ComplexOperator "!=" -> return! parseBinary BinaryKind.NotEqual | _ -> return expr } member x.ParseNextCommand() = x.ParseSingleCommand() member x.ParseNextLine() = let parseResult = x.ParseSingleLine() parseResult member x.ParseRange rangeText = x.Reset [|rangeText|] x.ParseLineRange(), x.ParseRestOfLine() member x.ParseExpression (expressionText: string) = x.Reset [|expressionText|] x.ParseExpressionCore() member x.ParseLineCommand commandText = x.Reset [|commandText|] x.ParseSingleCommand() member x.ParseLineCommands lines = x.Reset lines let rec inner rest = let lineCommand = x.ParseSingleCommand() if not x.IsDone then inner (fun item -> rest (lineCommand :: item)) else rest [lineCommand] inner (fun all -> all) member x.ParseFileNameModifiers : FileNameModifier list = let rec inner (modifiers:FileNameModifier list) : FileNameModifier list = match _tokenizer.CurrentTokenKind with | TokenKind.Character ':' -> let mark = _tokenizer.Mark _tokenizer.MoveNextChar() let c = _tokenizer.CurrentChar _tokenizer.MoveNextChar() match FileNameModifier.OfChar c with | Some m -> match m with | FileNameModifier.PathFull when modifiers.IsEmpty -> // Note that 'p' is only valid when it is the first modifier -- violations end the modifier sequence inner (m::modifiers) | FileNameModifier.Tail when not (List.exists (fun m -> m = FileNameModifier.Root || m = FileNameModifier.Extension || m = FileNameModifier.Tail) modifiers) -> // 't' must precede 'r' and 'e' and cannot be repeated -- violations end the modifier sequence inner (m::modifiers) | FileNameModifier.Head when not (List.exists (fun m -> m = FileNameModifier.Root || m = FileNameModifier.Extension || m = FileNameModifier.Tail) modifiers) -> // 'h' should not follow 'e', 't', or 'r' inner (m::modifiers) | FileNameModifier.Root -> inner (m::modifiers) | FileNameModifier.Extension -> inner (m::modifiers) | _ -> // Stop processing if we encounter an unrecognized modifier character. Unconsume the last character and yield the modifiers so far. _tokenizer.MoveToMark mark modifiers | None -> _tokenizer.MoveToMark mark modifiers | _ -> modifiers List.rev (inner List.Empty) member x.ParseDirectoryPath directoryPath : SymbolicPath = _tokenizer.Reset directoryPath TokenizerFlags.None let rec inner components = if _tokenizer.IsAtEndOfLine then components else match _tokenizer.CurrentTokenKind with | TokenKind.Character '\\' -> // As per :help cmdline-special, '\' only acts as an escape character when it immediately preceeds '%' or '#'. _tokenizer.MoveNextChar() match _tokenizer.CurrentTokenKind with | TokenKind.Character '#' | TokenKind.Character '%' -> let c = _tokenizer.CurrentChar _tokenizer.MoveNextChar() inner (SymbolicPathComponent.Literal (StringUtil.OfChar c)::components) | _ -> inner (SymbolicPathComponent.Literal "\\"::components) | TokenKind.Character '%' -> _tokenizer.MoveNextChar() let modifiers = SymbolicPathComponent.CurrentFileName x.ParseFileNameModifiers inner (modifiers::components) | TokenKind.Character '#' -> _tokenizer.MoveNextChar() let n = match _tokenizer.CurrentTokenKind with | TokenKind.Number n -> _tokenizer.MoveNextToken() n | _ -> 1 let modifiers = x.ParseFileNameModifiers inner (SymbolicPathComponent.AlternateFileName (n, modifiers)::components) | _ -> let literal = _tokenizer.CurrentToken.TokenText _tokenizer.MoveNextToken() let nextComponents = match components with | SymbolicPathComponent.Literal lhead::tail -> (SymbolicPathComponent.Literal (lhead + literal))::tail | _ -> (SymbolicPathComponent.Literal literal::components) inner nextComponents List.rev (inner List.Empty) and ConditionalParser ( _parser: Parser, _initialExpr: Expression ) = static let StateBeforeElse = 1 static let StateAfterElse = 2 let mutable _currentExpr = Some _initialExpr let mutable _currentCommands = List<LineCommand>() let mutable _builder = List<ConditionalBlock>() let mutable _state = StateBeforeElse member x.IsDone = _parser.IsDone member x.Parse() = let mutable error: string option = None let mutable isDone = false while not _parser.IsDone && not isDone && Option.isNone error do match _parser.ParseSingleCommand() with | LineCommand.Else -> if _state = StateAfterElse then error <- Some Resources.Parser_MultipleElse x.CreateConditionalBlock() _state <- StateAfterElse | LineCommand.ElseIf expr -> if _state = StateAfterElse then error <- Some Resources.Parser_ElseIfAfterElse x.CreateConditionalBlock() _currentExpr <- Some expr | LineCommand.IfEnd -> x.CreateConditionalBlock() isDone <- true | lineCommand -> _currentCommands.Add(lineCommand) match isDone, error with | _, Some msg -> LineCommand.ParseError msg | false, None -> _parser.ParseError "Unmatched Conditional Block" | true, None -> _builder |> List.ofSeq |> LineCommand.If member x.CreateConditionalBlock() = let conditionalBlock = { Conditional = _currentExpr LineCommands = List.ofSeq _currentCommands } _builder.Add(conditionalBlock) _currentExpr <- None _currentCommands.Clear() diff --git a/Src/VimCore/Interpreter_Parser.fsi b/Src/VimCore/Interpreter_Parser.fsi index f1eca5c..89900a8 100644 --- a/Src/VimCore/Interpreter_Parser.fsi +++ b/Src/VimCore/Interpreter_Parser.fsi @@ -1,40 +1,42 @@ #light namespace Vim.Interpreter open Vim [<RequireQualifiedAccess>] type internal ParseResult<'T> = | Succeeded of Value: 'T | Failed of Error: string [<Sealed>] [<Class>] type internal Parser = new: vimData: IVimGlobalSettings * IVimData -> Parser new: vimData: IVimGlobalSettings * IVimData * lines: string[] -> Parser member IsDone: bool member ContextLineNumber: int /// Parse the next complete command from the source. Command pairs like :func and :endfunc /// will be returned as a single Function command. member ParseNextCommand: unit -> LineCommand /// Parse the next line from the source. Command pairs like :func and :endfunc will /// not be returned as a single command. Instead they will be returned as the individual /// items member ParseNextLine: unit -> LineCommand member ParseRange: rangeText: string -> LineRangeSpecifier * string member ParseExpression: expressionText: string -> ParseResult<Expression> member ParseLineCommand: commandText: string -> LineCommand member ParseLineCommands: lines: string[] -> LineCommand list - member TryExpand: command: string -> string option + /// This will expand out an abbreviated command name to the full name. For example + /// will expand 'e' to 'edit'. + member TryExpandCommandName: shortCommandName: string -> string option diff --git a/Src/VimCore/Modes_Command_CommandMode.fs b/Src/VimCore/Modes_Command_CommandMode.fs index 4447010..e27b7fe 100644 --- a/Src/VimCore/Modes_Command_CommandMode.fs +++ b/Src/VimCore/Modes_Command_CommandMode.fs @@ -1,202 +1,206 @@ #light namespace Vim.Modes.Command open Vim open Vim.Interpreter open Microsoft.VisualStudio.Text open System.Text.RegularExpressions type internal CommandMode ( _buffer: IVimBuffer, _operations: ICommonOperations ) = let _commandChangedEvent = StandardEvent() let _commandRanEvent = StandardEvent<CommandEventArgs>() let _vimData = _buffer.VimData let _statusUtil = _buffer.VimBufferData.StatusUtil let _parser = Parser(_buffer.Vim.GlobalSettings, _vimData) let _vimHost = _buffer.Vim.VimHost static let BindDataError: MappedBindData<int> = { KeyRemapMode = KeyRemapMode.None; MappedBindFunction = fun _ -> MappedBindResult.Error } let mutable _command = EditableCommand.Empty let mutable _historySession: IHistorySession<int, int> option = None let mutable _bindData = BindDataError let mutable _keepSelection = false let mutable _isPartialCommand = false /// Currently queued up editable command member x.EditableCommand with get() = _command and set value = if value <> _command then _command <- value _commandChangedEvent.Trigger x /// Currently queued up command string member x.Command with get() = x.EditableCommand.Text and set value = x.EditableCommand <- EditableCommand(value) member x.InPasteWait = match _historySession with | Some historySession -> historySession.InPasteWait | None -> false member x.ParseAndRunInput (command: string) (wasMapped: bool) = let command = if command.Length > 0 && command.[0] = ':' then command.Substring(1) else command let lineCommand = _parser.ParseLineCommand command // We clear the selection for all line commands except a host command, // which manages any selection clearing itself. match lineCommand with | LineCommand.HostCommand _ -> _keepSelection <- true | _ -> () let vimInterpreter = _buffer.Vim.GetVimInterpreter _buffer vimInterpreter.RunLineCommand lineCommand if not wasMapped then _vimData.LastCommandLine <- command _vimData.LastLineCommand <- Some lineCommand - _commandRanEvent.Trigger x (CommandEventArgs(command, wasMapped, lineCommand)) + let fullCommand = + match _parser.TryExpandCommandName command with + | Some c -> c + | None -> command + _commandRanEvent.Trigger x (CommandEventArgs(command, fullCommand, wasMapped, lineCommand)) // Command mode can be validly entered with the selection active. Consider // hitting ':' in Visual Mode. The selection should be cleared when leaving member x.MaybeClearSelection moveCaretToStart = let selection = _buffer.TextView.Selection if not selection.IsEmpty && not _buffer.TextView.IsClosed && not _keepSelection then if moveCaretToStart then let point = selection.StreamSelectionSpan.SnapshotSpan.Start TextViewUtil.ClearSelection _buffer.TextView TextViewUtil.MoveCaretToPoint _buffer.TextView point else TextViewUtil.ClearSelection _buffer.TextView member x.Process (keyInputData: KeyInputData) = match _bindData.MappedBindFunction keyInputData with | MappedBindResult.Complete _ -> _bindData <- BindDataError // It is possible for the execution of the command to change the mode (say :s.../c) if _buffer.ModeKind = ModeKind.Command then if _isPartialCommand then ProcessResult.OfModeKind ModeKind.Normal else ProcessResult.Handled ModeSwitch.SwitchPreviousMode else ProcessResult.Handled ModeSwitch.NoSwitch | MappedBindResult.Cancelled -> _bindData <- BindDataError ProcessResult.OfModeKind ModeKind.Normal | MappedBindResult.Error -> _bindData <- BindDataError ProcessResult.OfModeKind ModeKind.Normal | MappedBindResult.NeedMoreInput bindData -> _bindData <- bindData ProcessResult.HandledNeedMoreInput member x.CreateHistorySession() = // The ProcessCommand call back just means a new command state was reached. Until it's // completed we just keep updating the current state let processCommand command = x.EditableCommand <- command 0 /// Run the specified command let completed command wasMapped = x.EditableCommand <- EditableCommand.Empty x.ParseAndRunInput command wasMapped x.MaybeClearSelection false 0 /// User cancelled input. Reset the selection let cancelled () = x.EditableCommand <- EditableCommand.Empty x.MaybeClearSelection true // First key stroke. Create a history client and get going let historyClient = { new IHistoryClient<int, int> with member this.HistoryList = _vimData.CommandHistory member this.RegisterMap = _buffer.RegisterMap member this.RemapMode = KeyRemapMode.Command member this.Beep() = _operations.Beep() member this.ProcessCommand _ command = processCommand command member this.Completed _ command wasMapped = completed command.Text wasMapped member this.Cancelled _ = cancelled () } HistoryUtil.CreateHistorySession historyClient 0 _command _buffer.VimTextBuffer.LocalAbbreviationMap _buffer.MotionUtil member x.OnEnter (arg: ModeArgument) = let historySession = x.CreateHistorySession() _command <- EditableCommand.Empty _historySession <- Some historySession _bindData <- historySession.CreateBindDataStorage().CreateMappedBindData() _keepSelection <- false _isPartialCommand <- false arg.CompleteAnyTransaction() let commandText = match arg with | ModeArgument.PartialCommand command -> _isPartialCommand <- true; command | _ -> StringUtil.Empty if not (StringUtil.IsNullOrEmpty commandText) then EditableCommand(commandText) |> x.ChangeCommand member x.OnLeave() = x.MaybeClearSelection true _command <- EditableCommand.Empty _historySession <- None _bindData <- BindDataError _keepSelection <- false _isPartialCommand <- false /// Called externally to update the command. Do this by modifying the history /// session. If we aren't in command mode currently then this is a no-op member x.ChangeCommand (command: EditableCommand) = match _historySession with | None -> () | Some historySession -> historySession.ResetCommand command interface ICommandMode with member x.VimTextBuffer = _buffer.VimTextBuffer member x.EditableCommand with get() = x.EditableCommand and set value = x.ChangeCommand value member x.Command with get() = x.Command and set value = EditableCommand(value) |> x.ChangeCommand member x.CommandNames = HistoryUtil.CommandNames |> Seq.map KeyInputSetUtil.Single member x.InPasteWait = x.InPasteWait member x.ModeKind = ModeKind.Command member x.CanProcess keyInput = KeyInputUtil.IsCore keyInput && not keyInput.IsMouseKey member x.Process keyInputData = x.Process keyInputData member x.OnEnter arg = x.OnEnter arg member x.OnLeave () = x.OnLeave () member x.OnClose() = () member x.RunCommand command = x.ParseAndRunInput command true [<CLIEvent>] member x.CommandChanged = _commandChangedEvent.Publish [<CLIEvent>] member x.CommandRan = _commandRanEvent.Publish diff --git a/Test/VimCoreTest/CommandModeIntegrationTest.cs b/Test/VimCoreTest/CommandModeIntegrationTest.cs index 1c981df..ad32cbe 100644 --- a/Test/VimCoreTest/CommandModeIntegrationTest.cs +++ b/Test/VimCoreTest/CommandModeIntegrationTest.cs @@ -341,1027 +341,1028 @@ namespace Vim.UnitTest public void MoveFromOtherBuffer() { // Reported in issue #1982. Create("cat", "dog", "bear", ""); var otherBuffer = CreateVimBuffer("bat", "hat", "goose", ""); Vim.MarkMap.SetGlobalMark(Letter.A, otherBuffer.VimTextBuffer, 1, 0); RunCommand("'A m 2"); Assert.Equal(new[] { "cat", "dog", "hat", "bear", "" }, _vimBuffer.TextBuffer.GetLines()); Assert.Equal(new[] { "bat", "goose", "" }, otherBuffer.TextBuffer.GetLines()); } } public sealed class DeleteMarksTest : CommandModeIntegrationTest { private bool HasGlobalMark(Letter letter) { return Vim.MarkMap.GetGlobalMark(letter).IsSome(); } private bool HasLocalMark(LocalMark localMark) { return _vimBuffer.VimTextBuffer.GetLocalMark(localMark).IsSome(); } private bool HasLocalMark(Letter letter) { return HasLocalMark(LocalMark.NewLetter(letter)); } [WpfFact] public void DeleteGlobal() { Create("cat", "dog"); _vimBuffer.ProcessNotation("mA"); Assert.True(HasGlobalMark(Letter.A)); _vimBuffer.ProcessNotation(":delmarks A", enter: true); Assert.False(HasGlobalMark(Letter.A)); } [WpfFact] public void DeleteGlobalMany() { Create("cat", "dog"); _vimBuffer.ProcessNotation("mA"); _vimBuffer.ProcessNotation("mB"); Assert.True(HasGlobalMark(Letter.A)); _vimBuffer.ProcessNotation(":delmarks A B", enter: true); Assert.False(HasGlobalMark(Letter.A)); Assert.False(HasGlobalMark(Letter.B)); } [WpfFact] public void DeleteGlobalRange() { Create("cat", "dog"); _vimBuffer.ProcessNotation("mA"); _vimBuffer.ProcessNotation("mB"); Assert.True(HasGlobalMark(Letter.A)); _vimBuffer.ProcessNotation(":delmarks A-B", enter: true); Assert.False(HasGlobalMark(Letter.A)); Assert.False(HasGlobalMark(Letter.B)); } /// <summary> /// Normal delete range operation but include some invalid marks here. No errors /// should be issued /// </summary> [WpfFact] public void DeleteGlobalRangeWithInvalid() { Create("cat", "dog"); _vimBuffer.ProcessNotation("mA"); _vimBuffer.ProcessNotation("mB"); Assert.True(HasGlobalMark(Letter.A)); _vimBuffer.ProcessNotation(":delmarks A-C", enter: true); Assert.False(HasGlobalMark(Letter.A)); Assert.False(HasGlobalMark(Letter.B)); Assert.False(HasGlobalMark(Letter.C)); } [WpfFact] public void DeleteLocalMark() { Create("cat", "dog"); _vimBuffer.ProcessNotation("ma"); _vimBuffer.ProcessNotation("mb"); Assert.True(HasLocalMark(Letter.A)); Assert.True(HasLocalMark(Letter.B)); _vimBuffer.ProcessNotation(":delmarks a", enter: true); Assert.False(HasLocalMark(Letter.A)); Assert.True(HasLocalMark(Letter.B)); } [WpfFact] public void DeleteLocalMarkMany() { Create("cat", "dog"); _vimBuffer.ProcessNotation("ma"); _vimBuffer.ProcessNotation("mb"); Assert.True(HasLocalMark(Letter.A)); Assert.True(HasLocalMark(Letter.B)); _vimBuffer.ProcessNotation(":delmarks a b", enter: true); Assert.False(HasLocalMark(Letter.A)); Assert.False(HasLocalMark(Letter.B)); } [WpfFact] public void DeleteLocalMarkRange() { Create("cat", "dog"); _vimBuffer.ProcessNotation("ma"); _vimBuffer.ProcessNotation("mb"); Assert.True(HasLocalMark(Letter.A)); Assert.True(HasLocalMark(Letter.B)); _vimBuffer.ProcessNotation(":delmarks a-b", enter: true); Assert.False(HasLocalMark(Letter.A)); Assert.False(HasLocalMark(Letter.B)); } [WpfFact] public void DeleteLocalMarkNumber() { Create("cat", "dog"); _vimBuffer.ProcessNotation("ma"); _vimBuffer.ProcessNotation("mb"); Assert.True(HasLocalMark(Letter.A)); Assert.True(HasLocalMark(Letter.B)); _vimBuffer.ProcessNotation(":delmarks a-b", enter: true); Assert.False(HasLocalMark(Letter.A)); Assert.False(HasLocalMark(Letter.B)); } [WpfFact] public void DeleteAllMarks() { Create("cat", "dog"); _vimBuffer.ProcessNotation("ma"); _vimBuffer.ProcessNotation("mA"); Assert.True(HasLocalMark(Letter.A)); Assert.True(HasGlobalMark(Letter.A)); _vimBuffer.ProcessNotation(":delmarks!", enter: true); Assert.False(HasLocalMark(Letter.A)); Assert.True(HasGlobalMark(Letter.A)); } } public sealed class EditTest : CommandModeIntegrationTest { [WpfTheory] [InlineData("e")] [InlineData("edi")] public void NoArgumentsShouldReload(string command) { Create(""); var didReload = false; VimHost.ReloadFunc = _ => { didReload = true; return true; }; VimHost.IsDirtyFunc = _ => false; RunCommand(command); Assert.True(didReload); } [WpfFact] public void NoArgumentsButDirtyShouldError() { Create(""); VimHost.ReloadFunc = _ => throw new Exception(""); VimHost.IsDirtyFunc = _ => true; RunCommand("e"); Assert.Equal(Resources.Common_NoWriteSinceLastChange, _lastError); } [WpfFact] public void FilePathButDirtyShouldError() { Create("foo"); VimHost.IsDirtyFunc = _ => true; RunCommand("e cat.txt"); Assert.Equal(Resources.Common_NoWriteSinceLastChange, _lastError); } /// <summary> /// Can't figure out how to make this fail so just beeping now /// </summary> [WpfFact] public void NoArgumentsReloadFailsShouldBeep() { Create("foo"); VimHost.ReloadFunc = _ => false; VimHost.IsDirtyFunc = _ => false; RunCommand("e"); Assert.Equal(1, VimHost.BeepCount); } [WpfFact] public void FilePathShouldLoadIntoExisting() { Create(""); var didLoad = false; VimHost.LoadFileIntoExistingWindowFunc = (path, _) => { Assert.Equal("cat.txt", path); didLoad = true; return true; }; VimHost.IsDirtyFunc = _ => false; RunCommand("e cat.txt"); Assert.True(didLoad); } } public sealed class GlobalTest : CommandModeIntegrationTest { [WpfFact] public void DeleteSelected() { Create("cat", "dog", "cattle"); _vimBuffer.ProcessNotation(":g/cat/d", enter: true); Assert.Equal(new[] { "dog" }, _vimBuffer.TextBuffer.GetLines()); } [WpfFact] public void UpdateLastSearch() { Create("cat", "dog", "cattle"); _vimBuffer.VimData.LastSearchData = new SearchData("cat", SearchPath.Forward); _vimBuffer.ProcessNotation(":g/cat/echo", enter: true); Assert.Equal("cat", _vimBuffer.VimData.LastSearchData.Pattern); } [WpfFact] public void SpaceDoesntUseLastSearch() { Create("cat", "dog", "cattle", "big dog"); _vimBuffer.VimData.LastSearchData = new SearchData("cat", SearchPath.Forward); _vimBuffer.ProcessNotation(":g/ /d", enter: true); Assert.Equal(new[] { "cat", "dog", "cattle" }, _vimBuffer.TextBuffer.GetLines()); } /// <summary> /// By default the global command should use the last search pattern /// </summary> [WpfFact] public void Issue1626() { Create("cat", "dog", "cattle"); _vimBuffer.VimData.LastSearchData = new SearchData("cat", SearchPath.Forward); _vimBuffer.ProcessNotation(":g//d", enter: true); Assert.Equal(new[] { "dog" }, _vimBuffer.TextBuffer.GetLines()); } } public sealed class IncrementalSearchTest : CommandModeIntegrationTest { /// <summary> /// Make sure that we can handle the incremental search command from the command line /// Issue 1034 /// </summary> [WpfFact] public void ForwardSimple() { Create("cat", "dog", "fish"); RunCommandRaw(":/dog"); Assert.Equal(_textBuffer.GetLine(1).Start, _textView.GetCaretPoint()); } /// <summary> /// Make sure that we can handle the incremental search command from the command line /// </summary> [WpfFact] public void BackwardSimple() { Create("cat", "dog", "fish"); _textView.MoveCaretToLine(2); RunCommandRaw(":?dog"); Assert.Equal(_textBuffer.GetLine(1).Start, _textView.GetCaretPoint()); } [WpfFact] public void ForwardMatchingCurrentLine() { Create("cat dog fish", "dog", "fish"); RunCommandRaw(":/dog"); Assert.Equal(_textBuffer.GetLine(1).Start, _textView.GetCaretPoint()); } /// <summary> /// Make sure that we can handle the incremental search command from the command line /// </summary> [WpfFact] public void BackwardMatchingCurrentLine() { Create("cat", "dog", "fish dog cat"); _textView.MoveCaretToLine(2); RunCommandRaw(":?dog"); Assert.Equal(_textBuffer.GetLine(1).Start, _textView.GetCaretPoint()); } /// <summary> /// Make sure the match goes to the first non-whitespace character on the line /// </summary> [WpfFact] public void MatchNotOnColumnZero() { Create("cat", " dog", "fish"); RunCommandRaw(":/dog"); Assert.Equal(_textBuffer.GetPointInLine(1, 1), _textView.GetCaretPoint()); } /// <summary> /// The caret should not move to the word but instead to the first non-blank character /// of the line /// </summary> [WpfFact] public void MatchNotStartOfLine() { Create("cat", " big dog", "fish"); RunCommandRaw(":/dog"); Assert.Equal(_textBuffer.GetPointInLine(1, 1), _textView.GetCaretPoint()); } /// <summary> /// Executing an incremental search from the command line needs to update the last searched /// for term /// </summary> [WpfFact] public void Issue1146() { Create("cat", " dog", "dog"); RunCommandRaw(":/dog"); _vimBuffer.Process("n"); Assert.Equal(_textBuffer.GetLine(2).Start, _textView.GetCaretPoint()); } } public sealed class LastCommandLineTest : CommandModeIntegrationTest { [WpfFact] public void Simple() { Create(); RunCommandRaw(":/dog"); Assert.Equal("/dog", VimData.LastCommandLine); } [WpfFact] public void Error() { Create(); VimData.LastCommandLine = "test"; RunCommandRaw(":not_a_vim_command"); Assert.Equal("not_a_vim_command", VimData.LastCommandLine); } } public sealed class LineEdittingTest : CommandModeIntegrationTest { private readonly HistoryList _commandHistoryList; public LineEdittingTest() { _commandHistoryList = VimData.CommandHistory; } /// <summary> /// An empty command shouldn't be store in the command history /// </summary> [WpfFact] public void EmptyCommandsNotStored() { Create(""); RunCommand(""); Assert.Empty(VimData.CommandHistory); } [WpfFact] public void PreviousCommand() { Create(""); _commandHistoryList.Add("dog"); _vimBuffer.ProcessNotation(":<Up>"); Assert.Equal("dog", _commandMode.Command); } [WpfFact] public void PreviousCommandAlternateKeystroke() { Create(""); _commandHistoryList.Add("dog"); _vimBuffer.ProcessNotation(":<C-p>"); Assert.Equal("dog", _commandMode.Command); } [WpfFact] public void NextCommand() { Create(""); _commandHistoryList.AddRange("dog", "cat"); _vimBuffer.ProcessNotation(":<Up><Up><Down>"); Assert.Equal("cat", _commandMode.Command); } [WpfFact] public void NextCommandAlternateKeystroke() { Create(""); _commandHistoryList.AddRange("dog", "cat"); _vimBuffer.ProcessNotation(":<C-p><C-p><C-n>"); Assert.Equal("cat", _commandMode.Command); } [WpfFact] public void PreviousCommandAfterEmptyHistory() { Create(""); _commandHistoryList.AddRange("dog", "cat"); _vimBuffer.ProcessNotation(":<C-p><C-n><C-p><C-p>"); Assert.Equal("dog", _commandMode.Command); } [WpfFact] public void Backspace() { Create(""); _vimBuffer.ProcessNotation(":dogd<BS>"); Assert.Equal("dog", _commandMode.Command); } [WpfFact] public void BackspaceWithShift() { Create(""); _vimBuffer.ProcessNotation(":dogd<S-BS>"); Assert.Equal("dog", _commandMode.Command); } } public sealed class MoveToTests : CommandModeIntegrationTest { [WpfFact] public void SimpleCaseOfMovingLineOneBelow() { Create("cat", "dog", "bear"); RunCommand("m 2"); Assert.Equal("dog", _textBuffer.GetLine(0).GetText()); Assert.Equal("cat", _textBuffer.GetLine(1).GetText()); Assert.Equal("bear", _textBuffer.GetLine(2).GetText()); } /// <summary> /// The last line in the file seems to be an exception because it doesn't have a /// newline at the end /// </summary> [WpfFact] public void MoveToLastLineInFile() { Create("cat", "dog", "bear"); RunCommand("m 3"); Assert.Equal("dog", _textBuffer.GetLine(0).GetText()); Assert.Equal("bear", _textBuffer.GetLine(1).GetText()); Assert.Equal("cat", _textBuffer.GetLine(2).GetText()); } /// <summary> /// Specifying "line 0" should move to before the first line. /// </summary> [WpfFact] public void MoveToBeforeFirstLineInFile() { Create("cat", "dog", "bear"); _textView.MoveCaretToLine(2); RunCommand("m0"); Assert.Equal("bear", _textBuffer.GetLine(0).GetText()); Assert.Equal("cat", _textBuffer.GetLine(1).GetText()); Assert.Equal("dog", _textBuffer.GetLine(2).GetText()); } } public sealed class ParseAndRunTest : CommandModeIntegrationTest { private CommandEventArgs _lastCommandRanEventArgs; private int _commandRanCount; internal override void Create(params string[] lines) { base.Create(lines); _commandMode.CommandRan += (_, e) => { _lastCommandRanEventArgs = e; _commandRanCount++; }; } [WpfTheory] [InlineData("red", "red", "redo")] [InlineData("redo", "redo", "redo")] [InlineData("u", "u", "undo")] [InlineData("undo", "undo", "undo")] public void ParseAndRun(string typed, string expectedCommandRan, string expectedFullCommandName) { Create(); RunCommand(typed); Assert.Equal(1, _commandRanCount); - Assert.Equal(expectedCommandRan, _lastCommandRanEventArgs.Command); + Assert.Equal(expectedCommandRan, _lastCommandRanEventArgs.RawCommand); Assert.True(_vimInterpreter.TryExpandCommandName(expectedCommandRan, out string fullCommandName)); Assert.Equal(expectedFullCommandName, fullCommandName); + Assert.Equal(expectedFullCommandName, _lastCommandRanEventArgs.Command); } } public sealed class PasteTest : CommandModeIntegrationTest { [WpfFact] public void Simple() { Create(""); Vim.RegisterMap.GetRegister('c').UpdateValue("test"); _vimBuffer.ProcessNotation(":<C-r>c"); Assert.Equal("test", _commandMode.Command); } [WpfFact] public void InPasteWait() { Create(""); Vim.RegisterMap.GetRegister('c').UpdateValue("test"); _vimBuffer.ProcessNotation(":h<C-r>"); Assert.True(_commandMode.InPasteWait); _vimBuffer.ProcessNotation("c"); Assert.Equal("htest", _commandMode.Command); Assert.False(_commandMode.InPasteWait); } [WpfFact] public void InsertWordUnderCursor() { // :help c_CTRL-R_CTRL-W Create("dog-bark", "cat-meow", "bear-growl"); _textView.MoveCaretToLine(1); var initialCaret = _textView.Caret; var initialSelection = _textView.Selection; _vimBuffer.ProcessNotation(":<C-r><C-w>"); Assert.Equal("cat", _commandMode.Command); Assert.False(_commandMode.InPasteWait); Assert.Equal(initialCaret, _textView.Caret); Assert.Equal(initialSelection, _textView.Selection); } [WpfFact] public void InsertAllWordUnderCursor() { // :help c_CTRL-R_CTRL-A Create("dog-bark", "cat-meow", "bear-growl"); _textView.MoveCaretToLine(1); var initialCaret = _textView.Caret; var initialSelection = _textView.Selection; _vimBuffer.ProcessNotation(":<C-r><C-a>"); Assert.Equal("cat-meow", _commandMode.Command); Assert.False(_commandMode.InPasteWait); Assert.Equal(initialCaret, _textView.Caret); Assert.Equal(initialSelection, _textView.Selection); } } public sealed class SortTest : CommandModeIntegrationTest { internal override void Create(params string[] lines) { base.Create(lines); _vimBuffer.Vim.GlobalSettings.GlobalDefault = true; } [WpfFact] public void None() { Create("cat", "bat", "dog"); RunCommand("sort"); Assert.Equal(new[] { "bat", "cat", "dog" }, _textBuffer.GetLines()); } [WpfFact] public void NoneLineRange() { Create("xxx", "cat", "bat", "dog", "aaa"); RunCommand("2,4sort"); Assert.Equal(new[] { "xxx", "bat", "cat", "dog", "aaa" }, _textBuffer.GetLines()); } [WpfFact] public void NoneTrailingLineBreak() { Create("cat", "bat", "dog", ""); RunCommand("sort"); Assert.Equal(new[] { "bat", "cat", "dog", "" }, _textBuffer.GetLines()); } [WpfFact] public void NoneReverseOrder() { Create("cat", "bat", "dog"); RunCommand("sort!"); Assert.Equal(new[] { "dog", "cat", "bat" }, _textBuffer.GetLines()); } [WpfFact] public void IgnoreCase() { Create("cat", "bat", "dog", "BAT"); RunCommand("sort i"); Assert.Equal(new[] { "bat", "BAT", "cat", "dog" }, _textBuffer.GetLines()); } [WpfFact] public void IgnoreCaseReverseOrder() { Create("cat", "bat", "dog", "BAT"); RunCommand("sort! i"); Assert.Equal(new[] { "dog", "cat", "bat", "BAT" }, _textBuffer.GetLines()); } [WpfFact] public void ProjectSkip() { Create("aaa cat", "bbb bat", "ccc dog", "ddd bear"); RunCommand(@"sort/.../"); Assert.Equal(new[] { "bbb bat", "ddd bear", "aaa cat", "ccc dog" }, _textBuffer.GetLines()); } [WpfFact] public void ProjectSkipUnanchored() { Create("aaa cat", "bbb bat", "ccc dog", "ddd bear"); RunCommand(@"sort/ /"); Assert.Equal(new[] { "bbb bat", "ddd bear", "aaa cat", "ccc dog" }, _textBuffer.GetLines()); } [WpfFact] public void ProjectMatch() { Create("aaa cat", "bbb bat", "ccc dog", "ddd bear"); RunCommand(@"sort/ [a-z]\+/r"); Assert.Equal(new[] { "bbb bat", "ddd bear", "aaa cat", "ccc dog" }, _textBuffer.GetLines()); } [WpfFact] public void Unique() { Create("cat", "bat", "dog", "cat"); RunCommand("sort u"); Assert.Equal(new[] { "bat", "cat", "dog" }, _textBuffer.GetLines()); } [WpfFact] public void UniqueIgnoreCase() { Create("CAT", "bat", "dog", "cat"); RunCommand("sort ui"); Assert.Equal(new[] { "bat", "CAT", "dog" }, _textBuffer.GetLines()); } [WpfFact] public void Decimal() { Create("99", "1", "100", "42"); RunCommand("sort n"); Assert.Equal(new[] { "1", "42", "99", "100" }, _textBuffer.GetLines()); } [WpfFact] public void DecimalNegativeNumbers() { Create("99", "-1", "100", "-42"); RunCommand("sort n"); Assert.Equal(new[] { "-42", "-1", "99", "100" }, _textBuffer.GetLines()); } [WpfFact] public void DecimalMissingNumbers() { Create("cat", "1", "bat", "10", "2"); RunCommand("sort n"); Assert.Equal(new[] { "cat", "bat", "1", "2", "10" }, _textBuffer.GetLines()); } [WpfFact] public void DecimalLeadingCharacters() { Create("aaa 99", "bbb 1", "ccc 100", "ddd 42"); RunCommand("sort n"); Assert.Equal(new[] { "bbb 1", "ddd 42", "aaa 99", "ccc 100" }, _textBuffer.GetLines()); } [WpfFact] public void Hexidecimal() { Create("deadbeef", "0", "0xcdcd", "ff"); RunCommand("sort x"); Assert.Equal(new[] { "0", "ff", "0xcdcd", "deadbeef" }, _textBuffer.GetLines()); } [WpfFact] public void HexidecimalNegativeNumbers() { Create("deadbeef", "0", "-0xcdcd", "ff"); RunCommand("sort x"); Assert.Equal(new[] { "-0xcdcd", "0", "ff", "deadbeef" }, _textBuffer.GetLines()); } [WpfFact] public void Octal() { Create("0777", "0", "0664", "5"); RunCommand("sort o"); Assert.Equal(new[] { "0", "5", "0664", "0777" }, _textBuffer.GetLines()); } [WpfFact] public void Binary() { Create("111", "0", "10", "1"); RunCommand("sort b"); Assert.Equal(new[] { "0", "1", "10", "111" }, _textBuffer.GetLines()); } [WpfFact] public void Float() { Create("0.1234", "0", "99", "3.1415"); RunCommand("sort f"); Assert.Equal(new[] { "0", "0.1234", "3.1415", "99" }, _textBuffer.GetLines()); } [WpfFact] public void FloatTwoFields() { Create("0.1234 xxx", "0 xxx", "99 xxx", "3.1415 xxx"); RunCommand("sort f"); Assert.Equal(new[] { "0 xxx", "0.1234 xxx", "3.1415 xxx", "99 xxx" }, _textBuffer.GetLines()); } [WpfFact] public void FloatProjectSkip() { Create("xxx 0.1234", "xxx 0", "xxx 99", "xxx 3.1415"); RunCommand(@"sort/.../f"); Assert.Equal(new[] { "xxx 0", "xxx 0.1234", "xxx 3.1415", "xxx 99" }, _textBuffer.GetLines()); } [WpfFact] public void FloatProjectMatch() { Create("xxx 0.1234", "xxx 0", "xxx 99", "xxx 3.1415"); RunCommand(@"sort/[0-9.]\+/fr"); Assert.Equal(new[] { "xxx 0", "xxx 0.1234", "xxx 3.1415", "xxx 99" }, _textBuffer.GetLines()); } [WpfFact] public void FloatProjectSkipMissingFinalDelimiter() { Create("xxx 0.1234", "xxx 0", "xxx 99", "xxx 3.1415"); RunCommand(@"sort f/..."); Assert.Equal(new[] { "xxx 0", "xxx 0.1234", "xxx 3.1415", "xxx 99" }, _textBuffer.GetLines()); } [WpfFact] public void FloatProjectMatchFlagsBeforeAndAfter() { Create("xxx 0.1234", "xxx 0", "xxx 99", "xxx 3.1415"); RunCommand(@"sort f/[0-9.]\+/r"); Assert.Equal(new[] { "xxx 0", "xxx 0.1234", "xxx 3.1415", "xxx 99" }, _textBuffer.GetLines()); } [WpfFact] public void FloatProjectMatchAlternateDelimiter() { Create("xxx 0.1234", "xxx 0", "xxx 99", "xxx 3.1415"); RunCommand(@"sort,[0-9.]\+,fr"); Assert.Equal(new[] { "xxx 0", "xxx 0.1234", "xxx 3.1415", "xxx 99" }, _textBuffer.GetLines()); } } public abstract class SubstituteTest : CommandModeIntegrationTest { public sealed class GlobalDefaultTest : SubstituteTest { internal override void Create(params string[] lines) { base.Create(lines); _vimBuffer.Vim.GlobalSettings.GlobalDefault = true; } [WpfFact] public void Simple() { Create("cat bat"); RunCommand("s/a/o"); Assert.Equal("cot bot", _textBuffer.GetLine(0).GetText()); } [WpfFact] public void Invert() { Create("cat bat"); RunCommand("s/a/o/g"); Assert.Equal("cot bat", _textBuffer.GetLine(0).GetText()); } [WpfFact] public void Repeat() { Create("cat bat", "cat bat"); RunCommand("s/a/o"); _textView.MoveCaretToLine(1); RunCommand("s"); Assert.Equal(new[] { "cot bot", "cot bot" }, _textBuffer.GetLines()); } } public sealed class SubstituteMiscTest : SubstituteTest { /// <summary> /// Suppress errors shouldn't print anything /// </summary> [WpfFact] public void Substitute1() { Create("cat", "dog"); var sawError = false; _vimBuffer.ErrorMessage += delegate { sawError = true; }; RunCommand("s/z/o/e"); Assert.False(sawError); } /// <summary> /// Simple search and replace /// </summary> [WpfFact] public void Substitute2() { Create("cat bat", "dag"); RunCommand("s/a/o/g 2"); Assert.Equal("cot bot", _textBuffer.GetLine(0).GetText()); Assert.Equal("dog", _textBuffer.GetLine(1).GetText()); } /// <summary> /// Repeat of the last search with a new flag /// </summary> [WpfFact] public void Substitute3() { Create("cat bat", "dag"); _vimBuffer.VimData.LastSubstituteData = FSharpOption.Create(new SubstituteData("a", "o", SubstituteFlags.None)); RunCommand("s g 2"); Assert.Equal("cot bot", _textBuffer.GetLine(0).GetText()); Assert.Equal("dog", _textBuffer.GetLine(1).GetText()); } /// <summary> /// Testing the print option /// </summary> [WpfFact] public void Substitute4() { Create("cat bat", "dag"); var message = string.Empty; _vimBuffer.StatusMessage += (_, e) => { message = e.Message; }; RunCommand("s/a/b/p"); Assert.Equal("cbt bat", message); } /// <summary> /// Testing the print number option /// </summary> [WpfFact] public void Substitute6() { Create("cat bat", "dag"); var message = string.Empty; _vimBuffer.StatusMessage += (_, e) => { message = e.Message; }; RunCommand("s/a/b/#"); Assert.Equal(" 1 cbt bat", message); } /// <summary> /// Testing the print list option /// </summary> [WpfFact] public void Substitute7() { Create("cat bat", "dag"); var message = string.Empty; _vimBuffer.StatusMessage += (_, e) => { message = e.Message; }; RunCommand("s/a/b/l"); Assert.Equal("cbt bat$", message); } /// <summary> /// Verify we handle escaped back slashes correctly /// </summary> [WpfFact] public void WithBackslashes() { Create(@"\\\\abc\\\\def"); RunCommand(@"s/\\\{4\}/\\\\/g"); Assert.Equal(@"\\abc\\def", _textBuffer.GetLine(0).GetText()); } /// <summary> /// Convert a set of spaces into tabs with the '\t' replacement /// </summary> [WpfFact] public void TabsForSpaces() { Create(" "); RunCommand(@"s/ /\t"); Assert.Equal("\t ", _textBuffer.GetLine(0).GetText()); } /// <summary> /// Convert spaces into new lines with the '\r' replacement /// </summary> [WpfFact] public void SpacesToNewLine() { Create("dog chases cat"); RunCommand(@"s/ /\r/g"); Assert.Equal("dog", _textBuffer.GetLine(0).GetText()); Assert.Equal("chases", _textBuffer.GetLine(1).GetText()); Assert.Equal("cat", _textBuffer.GetLine(2).GetText()); } [WpfFact] public void DefaultsToMagicMode() { Create("a.c", "abc"); RunCommand(@"%s/a\.c/replaced/g"); Assert.Equal("replaced", _textBuffer.GetLine(0).GetText()); Assert.Equal("abc", _textBuffer.GetLine(1).GetText()); } /// <summary> /// Make sure the "\1" does a group substitution instead of pushing in the literal 1 /// </summary> [WpfFact] public void ReplaceWithGroup() { Create(@"cat (dog)"); RunCommand(@"s/(\(\w\+\))/\1/"); Assert.Equal(@"cat dog", _textBuffer.GetLine(0).GetText()); } [WpfFact] public void NewlinesCanBeReplaced() { Create("foo", "bar"); RunCommand(@"%s/\n/ /"); Assert.Equal("foo bar", _textBuffer.GetLine(0).GetText()); } [WpfFact] public void MultilineReplaceFirstLine() { Create("foo", "bar", "baz"); RunCommand(@"s/foo\nbar/qux/"); Assert.Equal(new[] { "qux", "baz" }, _textBuffer.GetLines()); } [WpfFact] public void MultilineReplaceWholeBufferAtBeginning() { Create("foo", "bar", "baz"); RunCommand(@"%s/foo\nbar/qux/"); Assert.Equal(new[] { "qux", "baz" }, _textBuffer.GetLines()); } [WpfFact] public void MultilineReplaceWholeBufferAtEnd() { Create("foo", "bar", "baz"); RunCommand(@"%s/bar\nbaz/qux/"); Assert.Equal(new[] { "foo", "qux" }, _textBuffer.GetLines()); } [WpfFact] public void MultilineReplaceWholeShebang() { Create("foo", "bar", "baz", "qux"); RunCommand(@"s/foo\_.*qux/xyzzy/"); Assert.Equal(new[] { "xyzzy" }, _textBuffer.GetLines()); } [WpfFact] public void ReplaceInVisualSelection() { // Reported in issue #2147. Create(" foo bar baz qux "); _vimBuffer.Process("wv4e"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("foo bar baz qux", _textView.GetSelectionSpan().GetText()); RunCommand(@"s/\%V /_/g"); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); Assert.Equal(new[] { " foo_bar_baz_qux " }, _textBuffer.GetLines()); } [WpfFact] public void ReplaceInPreviousVisualSelection() { // Reported in issue #2147. Create(" foo bar baz qux "); _vimBuffer.Process("wv4e"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("foo bar baz qux", _textView.GetSelectionSpan().GetText()); _vimBuffer.ProcessNotation("<Esc>"); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); RunCommand(@"s/\%V /_/g"); Assert.Equal(new[] { " foo_bar_baz_qux " }, _textBuffer.GetLines()); } diff --git a/Test/VimCoreTest/ParserTest.cs b/Test/VimCoreTest/ParserTest.cs index 41e8bca..a6e7722 100644 --- a/Test/VimCoreTest/ParserTest.cs +++ b/Test/VimCoreTest/ParserTest.cs @@ -1437,573 +1437,573 @@ let x = 42 Assert.Equal(keyRemapModes, map.KeyRemapModes.ToArray()); Assert.Equal(allowRemap, map.AllowRemap); } private void AssertUnmap(string command, string keyNotation, params KeyRemapMode[] keyRemapModes) { var map = ParseLineCommand(command).AsUnmapKeys(); Assert.Equal(keyNotation, map.KeyNotation); Assert.Equal(keyRemapModes, map.KeyRemapModes.ToArray()); } [Fact] public void Default() { var modes = new KeyRemapMode[] { KeyRemapMode.Normal, KeyRemapMode.Visual, KeyRemapMode.Select, KeyRemapMode.OperatorPending }; AssertMap("noremap l h", "l", "h", modes); AssertMap("nore l h", "l", "h", modes); AssertMap("no l h", "l", "h", modes); } [Fact] public void DefaultWithBang() { var modes = new KeyRemapMode[] { KeyRemapMode.Insert, KeyRemapMode.Command }; AssertMap("noremap! l h", "l", "h", modes); AssertMap("nore! l h", "l", "h", modes); AssertMap("no! l h", "l", "h", modes); } /// <summary> /// Make sure that we can handle a double quote in the left side of an argument and /// that it's not interpreted as a comment /// </summary> [Fact] public void DoubleQuotesInLeft() { AssertMapWithRemap(@"imap "" dog", @"""", "dog", KeyRemapMode.Insert); AssertMapWithRemap(@"imap ""h dog", @"""h", "dog", KeyRemapMode.Insert); AssertMapWithRemap(@"imap a""h dog", @"a""h", "dog", KeyRemapMode.Insert); } /// <summary> /// Make sure that we can handle a double quote in the right side of an argument and /// that it's not interpreted as a comment /// </summary> [Fact] public void DoubleQuotesInRight() { AssertMapWithRemap(@"imap d """, "d", @"""", KeyRemapMode.Insert); AssertMapWithRemap(@"imap d h""", "d", @"h""", KeyRemapMode.Insert); AssertMapWithRemap(@"imap d h""a", "d", @"h""a", KeyRemapMode.Insert); } [Fact] public void Normal() { AssertMap("nnoremap l h", "l", "h", KeyRemapMode.Normal); AssertMap("nnor l h", "l", "h", KeyRemapMode.Normal); AssertMap("nn l h", "l", "h", KeyRemapMode.Normal); } [Fact] public void VirtualAndSelect() { AssertMap("vnoremap a b", "a", "b", KeyRemapMode.Visual, KeyRemapMode.Select); AssertMap("vnor a b", "a", "b", KeyRemapMode.Visual, KeyRemapMode.Select); AssertMap("vn a b", "a", "b", KeyRemapMode.Visual, KeyRemapMode.Select); } [Fact] public void Visual() { AssertMap("xnoremap b c", "b", "c", KeyRemapMode.Visual); } [Fact] public void Select() { AssertMap("snoremap a b", "a", "b", KeyRemapMode.Select); } [Fact] public void OperatorPending() { AssertMap("onoremap a b", "a", "b", KeyRemapMode.OperatorPending); } [Fact] public void Insert() { AssertMap("inoremap a b", "a", "b", KeyRemapMode.Insert); } /// <summary> /// Make sure the map commands can handle the special argument /// </summary> [Fact] public void Arguments() { void action(string commandText, KeyMapArgument mapArgument) { var command = ParseLineCommand(commandText).AsMapKeys(); var mapArguments = command.KeyMapArguments; Assert.Equal(1, mapArguments.Length); Assert.Equal(mapArgument, mapArguments.Head); } action("map <buffer> a b", KeyMapArgument.Buffer); action("map <silent> a b", KeyMapArgument.Silent); action("imap <silent> a b", KeyMapArgument.Silent); action("nmap <silent> a b", KeyMapArgument.Silent); } /// <summary> /// Make sure we can parse out all of the map special argument values /// </summary> [Fact] public void ArgumentsAll() { var all = new[] { "buffer", "silent", "expr", "unique", "special" }; foreach (var cur in all) { var parser = CreateParser("<" + cur + ">"); var list = parser.ParseMapArguments(); Assert.Equal(1, list.Length); } } /// <summary> /// Make sure we can parse out several items in a row and in the correct order /// </summary> [Fact] public void ArgumentsMultiple() { var text = "<buffer> <silent>"; var parser = CreateParser(text); var list = parser.ParseMapArguments().ToList(); Assert.Equal( new[] { KeyMapArgument.Buffer, KeyMapArgument.Silent }, list); } [Fact] public void RemapStandard() { AssertMapWithRemap("map a bc", "a", "bc", KeyRemapMode.Normal, KeyRemapMode.Visual, KeyRemapMode.Select, KeyRemapMode.OperatorPending); } [Fact] public void RemapNormal() { AssertMapWithRemap("nmap a b", "a", "b", KeyRemapMode.Normal); } [Fact] public void RemapMany() { AssertMapWithRemap("vmap a b", "a", "b", KeyRemapMode.Visual, KeyRemapMode.Select); AssertMapWithRemap("vm a b", "a", "b", KeyRemapMode.Visual, KeyRemapMode.Select); AssertMapWithRemap("xmap a b", "a", "b", KeyRemapMode.Visual); AssertMapWithRemap("xm a b", "a", "b", KeyRemapMode.Visual); AssertMapWithRemap("smap a b", "a", "b", KeyRemapMode.Select); AssertMapWithRemap("omap a b", "a", "b", KeyRemapMode.OperatorPending); AssertMapWithRemap("om a b", "a", "b", KeyRemapMode.OperatorPending); AssertMapWithRemap("imap a b", "a", "b", KeyRemapMode.Insert); AssertMapWithRemap("im a b", "a", "b", KeyRemapMode.Insert); AssertMapWithRemap("cmap a b", "a", "b", KeyRemapMode.Command); AssertMapWithRemap("cm a b", "a", "b", KeyRemapMode.Command); AssertMapWithRemap("lmap a b", "a", "b", KeyRemapMode.Language); AssertMapWithRemap("lm a b", "a", "b", KeyRemapMode.Language); AssertMapWithRemap("map! a b", "a", "b", KeyRemapMode.Insert, KeyRemapMode.Command); } /// <summary> /// Parse out the unmapping of keys /// </summary> [Fact] public void UnmapSimple() { AssertUnmap("vunmap a ", "a", KeyRemapMode.Visual, KeyRemapMode.Select); AssertUnmap("vunm a ", "a", KeyRemapMode.Visual, KeyRemapMode.Select); AssertUnmap("xunmap a", "a", KeyRemapMode.Visual); AssertUnmap("xunm a ", "a", KeyRemapMode.Visual); AssertUnmap("sunmap a ", "a", KeyRemapMode.Select); AssertUnmap("ounmap a ", "a", KeyRemapMode.OperatorPending); AssertUnmap("ounm a ", "a", KeyRemapMode.OperatorPending); AssertUnmap("iunmap a ", "a", KeyRemapMode.Insert); AssertUnmap("iunm a", "a", KeyRemapMode.Insert); AssertUnmap("cunmap a ", "a", KeyRemapMode.Command); AssertUnmap("cunm a ", "a", KeyRemapMode.Command); AssertUnmap("lunmap a ", "a", KeyRemapMode.Language); AssertUnmap("lunm a ", "a", KeyRemapMode.Language); AssertUnmap("unmap! a ", "a", KeyRemapMode.Insert, KeyRemapMode.Command); } } public sealed class ShiftTest : ParserTest { [Fact] public void ShiftLeft() { var command = ParseLineCommand("<"); Assert.True(command.IsShiftLeft); } [Fact] public void ShiftRight() { var command = ParseLineCommand(">"); Assert.True(command.IsShiftRight); } [Fact] public void ShiftRightWithRange() { var command = ParseLineCommand("'a,'b>"); Assert.True(command.IsShiftRight); var shift = (LineCommand.ShiftRight)command; Assert.True(shift.LineRangeSpecifier.IsRange); Assert.Equal(1, shift.Count); } [Fact] public void ShiftRightWithRangeAndSpace() { var command = ParseLineCommand("'a,'b >"); Assert.True(command.IsShiftRight); var shift = (LineCommand.ShiftRight)command; Assert.True(shift.LineRangeSpecifier.IsRange); Assert.Equal(1, shift.Count); } [Fact] public void ShiftDoubleLeft() { var command = ParseLineCommand("<<"); Assert.Equal(2, ((LineCommand.ShiftLeft)command).Count); } [Fact] public void ShiftDoubleRight() { var command = ParseLineCommand(">>"); Assert.Equal(2, ((LineCommand.ShiftRight)command).Count); } [Fact] public void ShiftTripleLeft() { var command = ParseLineCommand("<<<"); Assert.Equal(3, ((LineCommand.ShiftLeft)command).Count); } [Fact] public void ShiftTripleRight() { var command = ParseLineCommand(">>>"); Assert.Equal(3, ((LineCommand.ShiftRight)command).Count); } } public sealed class Misc : ParserTest { /// <summary> /// Change directory with an empty path /// </summary> [Fact] public void Parse_ChangeDirectory_Empty() { var command = ParseLineCommand("cd").AsChangeDirectory(); Assert.True(command.SymbolicPath.IsEmpty); } /// <summary> /// Change directory with a path /// </summary> [Fact] public void Parse_ChangeDirectory_Path() { var command = ParseLineCommand("cd test.txt").AsChangeDirectory(); Assert.Equal(1, command.SymbolicPath.Length); Assert.True(command.SymbolicPath.First().IsLiteral); Assert.Equal("test.txt", ((SymbolicPathComponent.Literal) command.SymbolicPath.First()).Literal); } /// <summary> /// Change directory with a path and a bang. The bang is ignored but legal in /// the grammar /// </summary> [Fact] public void Parse_ChangeDirectory_PathAndBang() { var command = ParseLineCommand("cd! test.txt").AsChangeDirectory(); Assert.Equal(1, command.SymbolicPath.Length); Assert.True(command.SymbolicPath.First().IsLiteral); Assert.Equal("test.txt", ((SymbolicPathComponent.Literal) command.SymbolicPath.First()).Literal); } /// <summary> /// ChangeLocal directory with an empty path /// </summary> [Fact] public void Parse_ChangeLocalDirectory_Empty() { var command = ParseLineCommand("lcd").AsChangeLocalDirectory(); Assert.True(command.SymbolicPath.IsEmpty); } /// <summary> /// ChangeLocal directory with a path /// </summary> [Fact] public void Parse_ChangeLocalDirectory_Path() { var command = ParseLineCommand("lcd test.txt").AsChangeLocalDirectory(); Assert.Equal(1, command.SymbolicPath.Length); Assert.True(command.SymbolicPath.First().IsLiteral); Assert.Equal("test.txt", ((SymbolicPathComponent.Literal) command.SymbolicPath.First()).Literal); } /// <summary> /// ChangeLocal directory with a path and a bang. The bang is ignored but legal in /// the grammar /// </summary> [Fact] public void Parse_ChangeLocalDirectory_PathAndBang() { var command = ParseLineCommand("lcd! test.txt").AsChangeLocalDirectory(); Assert.Equal(1, command.SymbolicPath.Length); Assert.True(command.SymbolicPath.First().IsLiteral); Assert.Equal("test.txt", ((SymbolicPathComponent.Literal) command.SymbolicPath.First()).Literal); } /// <summary> /// Make sure we can parse out the close command /// </summary> [Fact] public void Parse_Close_NoBang() { var command = ParseLineCommand("close"); Assert.True(command.IsClose); } /// <summary> /// Make sure we can parse out the close wit bang /// </summary> [Fact] public void Parse_Close_WithBang() { var command = ParseLineCommand("close!"); Assert.True(command.IsClose); Assert.True(command.AsClose().HasBang); } /// <summary> /// Make sure that we detect the trailing characters in the close command /// </summary> [Fact] public void Parse_Close_Trailing() { var lineCommand = VimUtil.ParseLineCommand("close foo"); Assert.True(lineCommand.IsParseError); Assert.Contains(Resources.CommandMode_TrailingCharacters, lineCommand.AsParseError().Error); } /// <summary> /// A line consisting of only a comment should parse as a nop /// </summary> [Fact] public void Parse_Nop_CommentLine() { Assert.True(ParseLineCommand(@" "" hello world").IsNop); } /// <summary> /// A line consisting of nothing should parse as a nop /// </summary> [Fact] public void Parse_Nop_EmptyLine() { Assert.True(ParseLineCommand(@"").IsNop); } /// <summary> /// Make sure we can handle the count argument of :delete /// </summary> [Fact] public void Parse_Delete_WithCount() { var lineCommand = ParseLineCommand("delete 2"); var lineRange = lineCommand.AsDelete().LineRangeSpecifier; Assert.Equal(2, lineRange.AsWithEndCount().Count); } [Fact] public void Parse_PrintCurrentDirectory() { var command = ParseLineCommand("pwd"); Assert.True(command.IsPrintCurrentDirectory); } [Fact] public void Parse_ReadCommand_Simple() { var command = ParseLineCommand("read !echo bar").AsReadCommand(); Assert.Equal("echo bar", command.CommandText); } [Fact] public void Parse_ReadFile_Simple() { var command = ParseLineCommand("read test.txt").AsReadFile(); Assert.Equal("test.txt", command.FilePath); } /// <summary> /// Parse out a source command with the specified name and no bang flag /// </summary> [Fact] public void Parse_Source_Simple() { var command = ParseLineCommand("source test.txt").AsSource(); Assert.False(command.HasBang); Assert.Equal("test.txt", command.FilePath); } /// <summary> /// Parse out a source command with the specified name and bang flag /// </summary> [Fact] public void Parse_Source_WithBang() { var command = ParseLineCommand("source! test.txt").AsSource(); Assert.True(command.HasBang); Assert.Equal("test.txt", command.FilePath); } [Fact] public void Parse_Write_Simple() { var write = ParseLineCommand("w").AsWrite(); Assert.True(write.LineRangeSpecifier.IsNone); Assert.False(write.HasBang); Assert.True(write.FilePath.IsNone()); } /// <summary> /// Parse out the write command given a file option /// </summary> [Fact] public void Parse_Write_ToFile() { var write = ParseLineCommand("w example.txt").AsWrite(); Assert.True(write.LineRangeSpecifier.IsNone); Assert.False(write.HasBang); Assert.Equal("example.txt", write.FilePath.Value); } [Fact] public void Parse_WriteAll_Simple() { var writeAll = ParseLineCommand("wall").AsWriteAll(); Assert.False(writeAll.HasBang); Assert.False(writeAll.Quit); } /// <summary> /// Parse out the :wall command with the ! option /// </summary> [Fact] public void Parse_WriteAll_WithBang() { var writeAll = ParseLineCommand("wall!").AsWriteAll(); Assert.True(writeAll.HasBang); Assert.False(writeAll.Quit); } [Fact] public void Parse_WriteQuitAll_Simple() { var writeAll = ParseLineCommand("wqall").AsWriteAll(); Assert.False(writeAll.HasBang); Assert.True(writeAll.Quit); } /// <summary> /// Parse out the :wall command with the ! option /// </summary> [Fact] public void Parse_WriteQuitAll_WithBang() { var writeAll = ParseLineCommand("wqall!").AsWriteAll(); Assert.True(writeAll.HasBang); Assert.True(writeAll.Quit); } /// <summary> /// Verify that we can parse out a yank command with a corresponding range /// </summary> [Fact] public void Parse_Yank_WithRange() { var yank = ParseLineCommand("'a,'by"); Assert.True(yank.IsYank); } /// <summary> /// When we pass in a full command name to try expand it shouldn't have any effect /// </summary> [Fact] public void TryExpand_Full() { var parser = CreateParser(""); - Assert.Equal("close", parser.TryExpand("close")); + Assert.Equal("close", parser.TryExpandCommandName("close")); } /// <summary> /// Make sure the abbreviation can be expanded /// </summary> [Fact] public void TryExpand_Abbreviation() { var parser = CreateParser(""); foreach (var tuple in Parser.s_LineCommandNamePair) { if (!string.IsNullOrEmpty(tuple.Item2)) { - Assert.Equal(tuple.Item1, parser.TryExpand(tuple.Item2)); + Assert.Equal(tuple.Item1, parser.TryExpandCommandName(tuple.Item2)); } } } [Fact] public void Version() { var command = ParseLineCommand("version"); Assert.True(command.IsVersion); } [Fact] public void Version_Short() { var command = ParseLineCommand("ve"); Assert.True(command.IsVersion); } [Fact] public void Registers() { void check(string text) { var command = ParseLineCommand(text); Assert.True(command.IsDisplayRegisters); } check("reg b 1"); check("reg"); check("reg a"); } [Fact] public void ErrorWindow() { Assert.Equal(new LineCommand.OpenListWindow(ListKind.Error), ParseLineCommand("cwindow")); } [Fact] public void LocationWindow() { Assert.Equal(new LineCommand.OpenListWindow(ListKind.Location), ParseLineCommand("lwindow")); } } } }
VsVim/VsVim
82352ddf828a2d7ef21b53514ee03a5ad71f563f
When adding or subtracting in visual mode, Skip invalid lines.
diff --git a/Src/VimCore/CommandUtil.fs b/Src/VimCore/CommandUtil.fs index 19e32e3..78f2639 100644 --- a/Src/VimCore/CommandUtil.fs +++ b/Src/VimCore/CommandUtil.fs @@ -1,704 +1,707 @@ #light namespace Vim open Vim.Modes open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Operations open Microsoft.VisualStudio.Text.Editor open Microsoft.VisualStudio.Text.Outlining open Microsoft.VisualStudio.Text.Formatting open System.Text open RegexPatternUtil open VimCoreExtensions open ITextEditExtensions open StringBuilderExtensions [<RequireQualifiedAccess>] [<NoComparison>] [<StructuralEquality>] type internal NumberValue = | Decimal of Decimal: int64 | Octal of Octal: uint64 | Hex of Hex: uint64 | Binary of Binary: uint64 | Alpha of Alpha: char with member x.NumberFormat = match x with | Decimal _ -> NumberFormat.Decimal | Octal _ -> NumberFormat.Octal | Hex _ -> NumberFormat.Hex | Binary _ -> NumberFormat.Binary | Alpha _ -> NumberFormat.Alpha /// There are some commands which if began in normal mode must end in normal /// mode (undo and redo). In general this is easy, don't switch modes. But often /// the code needs to call out to 3rd party code which can change the mode by /// altering the selection. /// /// This is a simple IDisposable type which will put us back into normal mode /// if this happens. type internal NormalModeSelectionGuard ( _vimBufferData: IVimBufferData ) = let _beganInNormalMode = _vimBufferData.VimTextBuffer.ModeKind = ModeKind.Normal member x.Dispose() = let selection = _vimBufferData.TextView.Selection if _beganInNormalMode && not selection.IsEmpty then TextViewUtil.ClearSelection _vimBufferData.TextView _vimBufferData.VimTextBuffer.SwitchMode ModeKind.Normal ModeArgument.None |> ignore interface System.IDisposable with member x.Dispose() = x.Dispose() /// This type houses the functionality behind a large set of the available /// Vim commands. /// /// This type could be further broken down into 2-3 types (one util to support /// the commands for specific modes). But there is a lot of benefit to keeping /// them together as it reduces the overhead of sharing common infrastructure. /// /// I've debated back and forth about separating them out. Thus far though I've /// decided to keep them all together because while there is a large set of /// functionality here there is very little state. So long as I can keep the /// amount of stored state low here I believe it counters the size of the type type internal CommandUtil ( _vimBufferData: IVimBufferData, _motionUtil: IMotionUtil, _commonOperations: ICommonOperations, _foldManager: IFoldManager, _insertUtil: IInsertUtil, _bulkOperations: IBulkOperations, _lineChangeTracker: ILineChangeTracker ) = let _vimTextBuffer = _vimBufferData.VimTextBuffer let _wordUtil = _vimBufferData.WordUtil let _wordNavigator = _vimTextBuffer.WordNavigator let _textView = _vimBufferData.TextView let _textBuffer = _textView.TextBuffer let _bufferGraph = _textView.BufferGraph let _statusUtil = _vimBufferData.StatusUtil let _undoRedoOperations = _vimBufferData.UndoRedoOperations let _localSettings = _vimBufferData.LocalSettings let _windowSettings = _vimBufferData.WindowSettings let _globalSettings = _localSettings.GlobalSettings let _vim = _vimBufferData.Vim let _vimData = _vim.VimData let _vimHost = _vim.VimHost let _markMap = _vim.MarkMap let _registerMap = _vim.RegisterMap let _searchService = _vim.SearchService let _macroRecorder = _vim.MacroRecorder let _jumpList = _vimBufferData.JumpList let _editorOperations = _commonOperations.EditorOperations let _options = _commonOperations.EditorOptions let mutable _inRepeatLastChange = false /// The last mouse down position before it was adjusted for virtual edit let mutable _leftMouseDownPoint: VirtualSnapshotPoint option = None /// Whether to select by word when dragging the mouse let mutable _doSelectByWord = false /// The SnapshotPoint for the caret member x.CaretPoint = TextViewUtil.GetCaretPoint _textView /// The VirtualSnapshotPoint for the caret member x.CaretVirtualPoint = TextViewUtil.GetCaretVirtualPoint _textView /// The column of the caret member x.CaretColumn = TextViewUtil.GetCaretColumn _textView /// The virtual column of the caret member x.CaretVirtualColumn = VirtualSnapshotColumn(x.CaretVirtualPoint) /// The ITextSnapshotLine for the caret member x.CaretLine = TextViewUtil.GetCaretLine _textView /// The line number for the caret member x.CaretLineNumber = x.CaretLine.LineNumber /// The SnapshotLineRange for the caret line member x.CaretLineRange = x.CaretLine |> SnapshotLineRangeUtil.CreateForLine /// The SnapshotPoint and ITextSnapshotLine for the caret member x.CaretPointAndLine = TextViewUtil.GetCaretPointAndLine _textView /// The current ITextSnapshot instance for the ITextBuffer member x.CurrentSnapshot = _textBuffer.CurrentSnapshot /// Add a new caret at the mouse point member x.AddCaretAtMousePoint () = _commonOperations.AddCaretAtMousePoint() CommandResult.Completed ModeSwitch.NoSwitch /// Add a new caret on an adjacent line in the specified direction member x.AddCaretOnAdjacentLine direction = _commonOperations.AddCaretOrSelectionOnAdjacentLine direction CommandResult.Completed ModeSwitch.NoSwitch /// Add a new selection on an adjacent line in the specified direction member x.AddSelectionOnAdjacentLine direction = _commonOperations.AddCaretOrSelectionOnAdjacentLine direction CommandResult.Completed ModeSwitch.NoSwitch /// Add count values to the specific word member x.AddToWord count = match x.AddToWordAtPointInSpan x.CaretPoint x.CaretLine.Extent count with | Some (span, text) -> // Need a transaction here in order to properly position the caret. // After the add the caret needs to be positioned on the last // character in the number. x.EditWithUndoTransaction "Add to word" (fun () -> _textBuffer.Replace(span.Span, text) |> ignore let position = span.Start.Position + text.Length - 1 TextViewUtil.MoveCaretToPosition _textView position) | None -> _commonOperations.Beep() CommandResult.Completed ModeSwitch.NoSwitch /// Add count to the word in each line of the selection, optionally progressively member x.AddToSelection (visualSpan: VisualSpan) count isProgressive = let startPoint = visualSpan.Start // Use a transaction to guarantee caret position. Caret should be at // the start during undo and redo so move it before the edit TextViewUtil.MoveCaretToPoint _textView startPoint x.EditWithUndoTransaction "Add to selection" (fun () -> use edit = _textBuffer.CreateEdit() - visualSpan.PerLineSpans |> Seq.iteri (fun index span -> + let AddToWordAtPointInSpanAndIncrementIndex index (span:SnapshotSpan) = let countForIndex = if isProgressive then count * (index + 1) else count match x.AddToWordAtPointInSpan span.Start span countForIndex with | Some (span, text) -> edit.Replace(span.Span, text) |> ignore + index + 1 | None -> - ()) + index + + Seq.fold AddToWordAtPointInSpanAndIncrementIndex 0 visualSpan.PerLineSpans |> ignore let position = x.ApplyEditAndMapPosition edit startPoint.Position TextViewUtil.MoveCaretToPosition _textView position) CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Add count values to the specific word member x.AddToWordAtPointInSpan point span count: (SnapshotSpan * string) option = match x.GetNumberAtPointInSpan point span with | Some (numberValue, span) -> // Calculate the new value of the number. let numberText = span.GetText() let text = match numberValue with | NumberValue.Alpha c -> c |> CharUtil.AlphaAdd count |> StringUtil.OfChar | NumberValue.Decimal number -> let newNumber = number + int64(count) let width = if numberText.StartsWith("-0") || numberText.StartsWith("0") then let oldSignWidth = if numberText.StartsWith("-") then 1 else 0 let newSignWidth = if newNumber < 0L then 1 else 0 numberText.Length + newSignWidth - oldSignWidth else 1 sprintf "%0*d" width newNumber | NumberValue.Octal number -> let newNumber = number + uint64(count) sprintf "0%0*o" (numberText.Length - 1) newNumber | NumberValue.Hex number -> let prefix = numberText.Substring(0, 2) let width = numberText.Length - 2 let newNumber = number + uint64(count) // If the number has any uppercase digits, use uppercase // for the new number. if RegularExpressions.Regex.Match(numberText, @"[A-F]").Success then sprintf "%s%0*X" prefix width newNumber else sprintf "%s%0*x" prefix width newNumber | NumberValue.Binary number -> let prefix = numberText.Substring(0, 2) let width = numberText.Length - 2 let newNumber = number + uint64(count) // There are no overloads for unsigned integer types and // binary convert is always unsigned anyway. let formattedNumber = System.Convert.ToString(int64(newNumber), 2) prefix + formattedNumber.PadLeft(width, '0') Some (span, text) | None -> None /// Apply the ITextEdit and returned the mapped position value from the resulting /// ITextSnapshot into the current ITextSnapshot. /// /// A number of commands will edit the text and calculate the position of the caret /// based on the edits about to be made. It's possible for other extensions to listen /// to the events fired by an edit and make fix up edits. This code accounts for that /// and returns the position mapped into the current ITextSnapshot member x.ApplyEditAndMapPoint (textEdit: ITextEdit) position = let editSnapshot = textEdit.Apply() SnapshotPoint(editSnapshot, position) |> _commonOperations.MapPointNegativeToCurrentSnapshot member x.ApplyEditAndMapColumn (textEdit: ITextEdit) position = let point = x.ApplyEditAndMapPoint textEdit position SnapshotColumn(point) member x.ApplyEditAndMapPosition (textEdit: ITextEdit) position = let point = x.ApplyEditAndMapPoint textEdit position point.Position /// Calculate the new RegisterValue for the provided one for put with indent /// operations. member x.CalculateIdentStringData (registerValue: RegisterValue) = // Get the indent string to apply to the lines which are indented let indent = x.CaretLine |> SnapshotLineUtil.GetIndentText |> (fun text -> _commonOperations.NormalizeBlanks text 0) // Adjust the indentation on a given line of text to have the indentation // previously calculated let adjustTextLine (textLine: TextLine) = let oldIndent = textLine.Text |> Seq.takeWhile CharUtil.IsBlank |> StringUtil.OfCharSeq let text = indent + (textLine.Text.Substring(oldIndent.Length)) { textLine with Text = text } // Really a put after with indent is just a normal put after of the adjusted // register value. So adjust here and forward on the magic let stringData = let stringData = registerValue.StringData match stringData with | StringData.Block _ -> // Block values don't participate in indentation of this manner stringData | StringData.Simple text -> match registerValue.OperationKind with | OperationKind.CharacterWise -> // We only change lines after the first. So break it into separate lines // fix their indent and then produce the new value. let lines = TextLine.GetTextLines text let head = lines.Head let rest = lines.Rest |> Seq.map adjustTextLine let text = let all = Seq.append (Seq.singleton head) rest TextLine.CreateString all StringData.Simple text | OperationKind.LineWise -> // Change every line for a line wise operation text |> TextLine.GetTextLines |> Seq.map adjustTextLine |> TextLine.CreateString |> StringData.Simple x.CreateRegisterValue stringData registerValue.OperationKind /// Calculate the VisualSpan value for the associated ITextBuffer given the /// StoreVisualSpan value member x.CalculateVisualSpan stored = match stored with | StoredVisualSpan.Line (Count = count) -> // Repeating a LineWise operation just creates a span with the same // number of lines as the original operation let range = SnapshotLineRangeUtil.CreateForLineAndMaxCount x.CaretLine count VisualSpan.Line range | StoredVisualSpan.Character (LineCount = lineCount; LastLineMaxPositionCount = lastLineMaxPositionCount) -> let characterSpan = CharacterSpan(x.CaretPoint, lineCount, lastLineMaxPositionCount) VisualSpan.Character characterSpan | StoredVisualSpan.Block (Width = width; Height = height; EndOfLine = endOfLine) -> // Need to rehydrate spans of length 'length' on 'count' lines from the // current caret position let blockSpan = BlockSpan(x.CaretVirtualPoint, _localSettings.TabStop, width, height, endOfLine) VisualSpan.Block blockSpan member x.CalculateDeleteOperation (result: MotionResult) = if Util.IsFlagSet result.MotionResultFlags MotionResultFlags.BigDelete then RegisterOperation.BigDelete else RegisterOperation.Delete member x.CancelOperation () = x.ClearSecondarySelections() _vimTextBuffer.SwitchMode ModeKind.Normal ModeArgument.CancelOperation CommandResult.Completed ModeSwitch.NoSwitch /// Change the characters in the given span via the specified change kind member x.ChangeCaseSpanCore kind (editSpan: EditSpan) = let func = match kind with | ChangeCharacterKind.Rot13 -> CharUtil.ChangeRot13 | ChangeCharacterKind.ToLowerCase -> CharUtil.ToLower | ChangeCharacterKind.ToUpperCase -> CharUtil.ToUpper | ChangeCharacterKind.ToggleCase -> CharUtil.ChangeCase use edit = _textBuffer.CreateEdit() editSpan.Spans |> Seq.map (SnapshotSpanUtil.GetPoints SearchPath.Forward) |> Seq.concat |> Seq.filter (fun p -> CharUtil.IsLetter (p.GetChar())) |> Seq.iter (fun p -> let change = func (p.GetChar()) |> StringUtil.OfChar edit.Replace(p.Position, 1, change) |> ignore) edit.Apply() |> ignore /// Change the caret line via the specified ChangeCharacterKind. member x.ChangeCaseCaretLine kind = // The caret should be positioned on the first non-blank space in // the line. If the line is completely blank the caret should // not be moved. Caret should be in the same place for undo / redo // so move before and inside the transaction let position = x.CaretLine |> SnapshotLineUtil.GetPoints SearchPath.Forward |> Seq.skipWhile SnapshotPointUtil.IsWhiteSpace |> Seq.map SnapshotPointUtil.GetPosition |> SeqUtil.tryHeadOnly let maybeMoveCaret () = match position with | Some position -> TextViewUtil.MoveCaretToPosition _textView position | None -> () maybeMoveCaret() x.EditWithUndoTransaction "Change" (fun () -> x.ChangeCaseSpanCore kind (EditSpan.Single (SnapshotColumnSpan(x.CaretLine))) maybeMoveCaret()) CommandResult.Completed ModeSwitch.NoSwitch /// Change the case of the specified motion member x.ChangeCaseMotion kind (result: MotionResult) = // The caret should be placed at the start of the motion for both // undo / redo so move before and inside the transaction TextViewUtil.MoveCaretToPoint _textView result.Span.Start x.EditWithUndoTransaction "Change" (fun () -> x.ChangeCaseSpanCore kind result.EditSpan TextViewUtil.MoveCaretToPosition _textView result.Span.Start.Position) CommandResult.Completed ModeSwitch.NoSwitch /// Change the case of the current caret point member x.ChangeCaseCaretPoint kind count = // The caret should be placed after the caret point but only // for redo. Undo should move back to the current position so // don't move until inside the transaction x.EditWithUndoTransaction "Change" (fun () -> let span = let endColumn = x.CaretColumn.AddInLineOrEnd(count) SnapshotColumnSpan(x.CaretColumn, endColumn) let editSpan = EditSpan.Single span x.ChangeCaseSpanCore kind editSpan // Move the caret but make sure to respect the 'virtualedit' option let point = SnapshotPoint(x.CurrentSnapshot, span.End.StartPosition) _commonOperations.MoveCaretToPoint point ViewFlags.VirtualEdit) CommandResult.Completed ModeSwitch.NoSwitch /// Change the case of the selected text. member x.ChangeCaseVisual kind (visualSpan: VisualSpan) = // The caret should be positioned at the start of the VisualSpan for both // undo / redo so move it before and inside the transaction let point = visualSpan.Start let moveCaret () = TextViewUtil.MoveCaretToPosition _textView point.Position moveCaret() x.EditWithUndoTransaction "Change" (fun () -> x.ChangeCaseSpanCore kind visualSpan.EditSpan moveCaret()) CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Delete the specified motion and enter insert mode member x.ChangeMotion registerName (result: MotionResult) = // This command has legacy / special case behavior for forward word motions. It will // not delete any trailing whitespace in the span if the motion is created for a forward // word motion. This behavior is detailed in the :help WORD section of the gVim // documentation and is likely legacy behavior coming from the original vi // implementation. A larger discussion thread is available here // http://groups.google.com/group/vim_use/browse_thread/thread/88b6499bbcb0878d/561dfe13d3f2ef63?lnk=gst&q=whitespace+cw#561dfe13d3f2ef63 let span = if result.IsAnyWordMotion && result.IsForward then let point = result.Span |> SnapshotSpanUtil.GetPoints SearchPath.Backward |> Seq.tryFind (fun x -> x.GetChar() |> CharUtil.IsWhiteSpace |> not) match point with | Some(p) -> let endPoint = p |> SnapshotPointUtil.TryAddOne |> OptionUtil.getOrDefault (SnapshotUtil.GetEndPoint (p.Snapshot)) SnapshotSpan(result.Span.Start, endPoint) | None -> result.Span elif result.OperationKind = OperationKind.LineWise then // If the change command ends inside a line break then the actual delete operation // is backed up so that it leaves a single blank line after the delete operation. This // allows the insert to begin on a blank line match SnapshotSpanUtil.GetLastIncludedPoint result.Span with | Some point -> if SnapshotPointUtil.IsInsideLineBreak point then let line = SnapshotPointUtil.GetContainingLine point SnapshotSpan(result.Span.Start, line.End) else result.Span | None -> result.Span else result.Span // Use an undo transaction to preserve the caret position. Experiments show that the rules // for caret undo should be // 1. start of the change if motion is character wise // 2. start of second line if motion is line wise let point = match result.MotionKind with | MotionKind.CharacterWiseExclusive -> span.Start | MotionKind.CharacterWiseInclusive -> span.Start | MotionKind.LineWise -> let startLine = SnapshotSpanUtil.GetStartLine span let line = SnapshotUtil.TryGetLine span.Snapshot (startLine.LineNumber + 1) |> OptionUtil.getOrDefault startLine line.Start TextViewUtil.MoveCaretToPoint _textView point let commandResult = x.EditWithLinkedChange "Change" (fun () -> let savedStartLine = SnapshotPointUtil.GetContainingLine span.Start _textBuffer.Delete(span.Span) |> ignore if result.MotionKind = MotionKind.LineWise then SnapshotUtil.GetLine x.CurrentSnapshot savedStartLine.LineNumber |> x.MoveCaretToNewLineIndent savedStartLine else span.Start.TranslateTo(_textBuffer.CurrentSnapshot, PointTrackingMode.Negative) |> TextViewUtil.MoveCaretToPoint _textView) // Now that the delete is complete update the register let value = x.CreateRegisterValue (StringData.OfSpan span) result.OperationKind let operation = x.CalculateDeleteOperation result _commonOperations.SetRegisterValue registerName operation value commandResult /// Delete 'count' lines and begin insert mode. The documentation of this command /// and behavior are a bit off. It's documented like it behaves like 'dd + insert mode' /// but behaves more like ChangeTillEndOfLine but linewise and deletes the entire /// first line member x.ChangeLines count registerName = let range = SnapshotLineRangeUtil.CreateForLineAndMaxCount x.CaretLine count x.ChangeLinesCore range registerName /// Core routine for changing a set of lines in the ITextBuffer. This is the backing function /// for changing lines in both normal and visual mode member x.ChangeLinesCore (range: SnapshotLineRange) registerName = // Caret position for the undo operation depends on the number of lines which are in // range being deleted. If there is a single line then we position it before the first // non space / tab character in the first line. If there is more than one line then we // position it at the equivalent location in the second line. // // There appears to be no logical reason for this behavior difference but it exists let savedStartLine = range.StartLine let point = let line = if range.Count = 1 then range.StartLine else SnapshotUtil.GetLine range.Snapshot (range.StartLineNumber + 1) line |> SnapshotLineUtil.GetPoints SearchPath.Forward |> Seq.skipWhile SnapshotPointUtil.IsBlank |> SeqUtil.tryHeadOnly match point with | None -> () | Some point -> TextViewUtil.MoveCaretToPoint _textView point // Start an edit transaction to get the appropriate undo / redo behavior for the // caret movement after the edit. x.EditWithLinkedChange "ChangeLines" (fun () -> // Actually delete the text and position the caret _textBuffer.Delete(range.Extent.Span) |> ignore let line = SnapshotUtil.GetLine x.CurrentSnapshot savedStartLine.LineNumber x.MoveCaretToNewLineIndent savedStartLine line // Update the register now that the operation is complete. Register value is odd here // because we really didn't delete linewise but it's required to be a linewise // operation. let stringData = range.Extent.GetText() |> StringData.Simple let value = x.CreateRegisterValue stringData OperationKind.LineWise _commonOperations.SetRegisterValue registerName RegisterOperation.Delete value) /// Delete the selected lines and begin insert mode (implements the 'S', 'C' and 'R' visual /// mode commands. This is very similar to DeleteLineSelection except that block deletion /// can be special cased depending on the command it's used in member x.ChangeLineSelection registerName (visualSpan: VisualSpan) specialCaseBlock = // The majority of cases simply delete a SnapshotLineRange directly. Handle that here let deleteRange (range: SnapshotLineRange) = // In an undo the caret position has 2 cases. // - Single line range: Start of the first line // - Multiline range: Start of the second line. let savedStartLine = range.StartLine let point = if range.Count = 1 then range.StartLine.Start else let next = SnapshotUtil.GetLine range.Snapshot (range.StartLineNumber + 1) next.Start TextViewUtil.MoveCaretToPoint _textView point let commandResult = x.EditWithLinkedChange "ChangeLines" (fun () -> _textBuffer.Delete(range.Extent.Span) |> ignore let line = SnapshotUtil.GetLine x.CurrentSnapshot savedStartLine.LineNumber x.MoveCaretToNewLineIndent savedStartLine line) (EditSpan.Single range.ColumnExtent, commandResult) // The special casing of block deletion is handled here let deleteBlock (col: NonEmptyCollection<SnapshotOverlapColumnSpan>) = // First step is to change the SnapshotSpan instances to extent from the start to the // end of the current line let col = col |> NonEmptyCollectionUtil.Map (fun span -> let endColumn = let endColumn = SnapshotColumn.GetLineEnd(span.Start.Line) SnapshotOverlapColumn(endColumn, _localSettings.TabStop) SnapshotOverlapColumnSpan(span.Start, endColumn, _localSettings.TabStop)) // Caret should be positioned at the start of the span for undo TextViewUtil.MoveCaretToPoint _textView col.Head.Start.Column.StartPoint let commandResult = x.EditWithLinkedChange "ChangeLines" (fun () -> let edit = _textBuffer.CreateEdit() col |> Seq.iter (fun span -> edit.Delete(span) |> ignore) let position = x.ApplyEditAndMapPosition edit col.Head.Start.Column.StartPosition TextViewUtil.MoveCaretToPosition _textView position) (EditSpan.Block col, commandResult) // Dispatch to the appropriate type of edit let editSpan, commandResult = match visualSpan with | VisualSpan.Character characterSpan -> characterSpan.Span |> SnapshotLineRangeUtil.CreateForSpan |> deleteRange | VisualSpan.Line range -> deleteRange range | VisualSpan.Block blockSpan -> if specialCaseBlock then deleteBlock blockSpan.BlockOverlapColumnSpans else visualSpan.EditSpan.OverarchingSpan |> SnapshotLineRangeUtil.CreateForSpan |> deleteRange let value = x.CreateRegisterValue (StringData.OfEditSpan editSpan) OperationKind.LineWise _commonOperations.SetRegisterValue registerName RegisterOperation.Delete value commandResult /// Delete till the end of the line and start insert mode member x.ChangeTillEndOfLine count registerName = // The actual text edit portion of this operation is identical to the // DeleteTillEndOfLine operation. There is a difference though in the // positioning of the caret. DeleteTillEndOfLine needs to consider the virtual // space settings since it remains in normal mode but change does not due // to it switching to insert mode let caretPosition = x.CaretPoint.Position x.EditWithLinkedChange "ChangeTillEndOfLine" (fun () -> x.DeleteTillEndOfLineCore count registerName // Move the caret back to it's original position. Don't consider virtual // space here since we're switching to insert mode let point = SnapshotPoint(x.CurrentSnapshot, caretPosition) _commonOperations.MoveCaretToPoint point ViewFlags.None) /// Delete the selected text in Visual Mode and begin insert mode with a linked /// transaction. member x.ChangeSelection registerName (visualSpan: VisualSpan) = match visualSpan with | VisualSpan.Character _ -> // For block and character modes the change selection command is simply a // delete of the span and move into insert mode. // // Caret needs to be positioned at the front of the span in undo so move it // before we create the transaction TextViewUtil.MoveCaretToPoint _textView visualSpan.Start x.EditWithLinkedChange "ChangeSelection" (fun() -> x.DeleteSelection registerName visualSpan |> ignore) | VisualSpan.Block blockSpan -> // Change in block mode has behavior very similar to Shift + Insert. It needs // to be a change followed by a transition into insert where the insert actions // are repeated across the block span // Caret needs to be positioned at the front of the span in undo so move it // before we create the transaction TextViewUtil.MoveCaretToPoint _textView visualSpan.Start x.EditBlockWithLinkedChange "Change Block" blockSpan VisualInsertKind.Start (fun () -> x.DeleteSelection registerName visualSpan |> ignore) | VisualSpan.Line range -> x.ChangeLinesCore range registerName /// Close a single fold under the caret member x.CloseFoldInSelection (visualSpan: VisualSpan) = let range = visualSpan.LineRange let offset = range.StartLineNumber for i = 0 to range.Count - 1 do let line = SnapshotUtil.GetLine x.CurrentSnapshot (offset + i) _foldManager.CloseFold line.Start 1 CommandResult.Completed ModeSwitch.NoSwitch /// Close 'count' folds under the caret member x.CloseFoldUnderCaret count = _foldManager.CloseFold x.CaretPoint count CommandResult.Completed ModeSwitch.NoSwitch /// Close all of the folds in the buffer member x.CloseAllFolds() = let span = SnapshotUtil.GetExtent x.CurrentSnapshot _foldManager.CloseAllFolds span CommandResult.Completed ModeSwitch.NoSwitch /// Close all folds under the caret member x.CloseAllFoldsUnderCaret () = let span = SnapshotSpan(x.CaretPoint, 0) _foldManager.CloseAllFolds span CommandResult.Completed ModeSwitch.NoSwitch /// Close all folds in the selection member x.CloseAllFoldsInSelection (visualSpan: VisualSpan) = diff --git a/Test/VimCoreTest/VisualModeIntegrationTest.cs b/Test/VimCoreTest/VisualModeIntegrationTest.cs index 1ba98b2..991db47 100644 --- a/Test/VimCoreTest/VisualModeIntegrationTest.cs +++ b/Test/VimCoreTest/VisualModeIntegrationTest.cs @@ -148,1042 +148,1042 @@ namespace Vim.UnitTest _testableMouseDevice.Point = startPoint; _vimBuffer.ProcessNotation("<LeftMouse>"); Assert.Equal(startPoint.Position, _textView.GetCaretPoint().Position); _vimBuffer.ProcessNotation("<LeftDrag>"); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); // still normal var midPoint = _textView.GetPointInLine(0, 5); // 'o' in 'dog' _testableMouseDevice.Point = midPoint; _vimBuffer.ProcessNotation("<LeftDrag>"); Assert.Equal("do", _textView.GetSelectionSpan().GetText()); Assert.Equal(midPoint.Position, _textView.GetCaretPoint().Position); var endPoint = _textView.GetPointInLine(0, 6); // 'g' in 'dog' _testableMouseDevice.Point = endPoint; _vimBuffer.ProcessNotation("<LeftRelease>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(endPoint.Position, _textView.GetCaretPoint().Position); } [WpfFact] public void InsertDrag() { Create("cat dog bear", ""); _textView.SetVisibleLineCount(2); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); var startPoint = _textView.GetPointInLine(0, 4); // 'd' in 'dog' _testableMouseDevice.Point = startPoint; _vimBuffer.ProcessNotation("<LeftMouse>"); Assert.Equal(startPoint.Position, _textView.GetCaretPoint().Position); _vimBuffer.ProcessNotation("<LeftDrag>"); Assert.Equal(ModeKind.Insert, _vimBuffer.ModeKind); // still insert var midPoint = _textView.GetPointInLine(0, 5); // 'o' in 'dog' _testableMouseDevice.Point = midPoint; _vimBuffer.ProcessNotation("<LeftDrag>"); Assert.Equal("do", _textView.GetSelectionSpan().GetText()); Assert.Equal(midPoint.Position, _textView.GetCaretPoint().Position); var endPoint = _textView.GetPointInLine(0, 6); // 'g' in 'dog' _testableMouseDevice.Point = endPoint; _vimBuffer.ProcessNotation("<LeftRelease>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(endPoint.Position, _textView.GetCaretPoint().Position); _testableMouseDevice.Point = startPoint; _vimBuffer.ProcessNotation("<LeftMouse><LeftRelease>"); Assert.Equal(startPoint.Position, _textView.GetCaretPoint().Position); Assert.Equal(ModeKind.Insert, _vimBuffer.ModeKind); // back to insert } [WpfFact] public void ExclusiveShiftClick() { Create("cat dog bear", ""); _textView.SetVisibleLineCount(2); _globalSettings.Selection = "exclusive"; var startPoint = _textView.GetPointInLine(0, 4); // 'd' in 'dog' _testableMouseDevice.Point = startPoint; _vimBuffer.ProcessNotation("<LeftMouse>"); Assert.Equal(startPoint.Position, _textView.GetCaretPoint().Position); var endPoint = _textView.GetPointInLine(0, 7); // ' ' after 'dog' _testableMouseDevice.Point = endPoint; _vimBuffer.ProcessNotation("<S-LeftMouse>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(endPoint.Position, _textView.GetCaretPoint().Position); } [WpfFact] public void InclusiveShiftClick() { Create("cat dog bear", ""); _textView.SetVisibleLineCount(2); _globalSettings.Selection = "inclusive"; var startPoint = _textView.GetPointInLine(0, 4); // 'd' in 'dog' _testableMouseDevice.Point = startPoint; _vimBuffer.ProcessNotation("<LeftMouse>"); Assert.Equal(startPoint.Position, _textView.GetCaretPoint().Position); var endPoint = _textView.GetPointInLine(0, 6); // 'g' in 'dog' _testableMouseDevice.Point = endPoint; _vimBuffer.ProcessNotation("<S-LeftMouse>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(endPoint.Position, _textView.GetCaretPoint().Position); } [WpfFact] public void InsertShiftClick() { Create("cat dog bear", ""); _textView.SetVisibleLineCount(2); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); var startPoint = _textView.GetPointInLine(0, 4); // 'd' in 'dog' _testableMouseDevice.Point = startPoint; _vimBuffer.ProcessNotation("<LeftMouse>"); Assert.Equal(startPoint.Position, _textView.GetCaretPoint().Position); var endPoint = _textView.GetPointInLine(0, 6); // 'g' in 'dog' _testableMouseDevice.Point = endPoint; _vimBuffer.ProcessNotation("<S-LeftMouse>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(endPoint.Position, _textView.GetCaretPoint().Position); _testableMouseDevice.Point = startPoint; _vimBuffer.ProcessNotation("<LeftMouse>"); Assert.Equal(startPoint.Position, _textView.GetCaretPoint().Position); Assert.Equal(ModeKind.Insert, _vimBuffer.ModeKind); // back to insert } [WpfFact] public void LinewiseShiftClick() { Create("cat dog bear", "pig horse bat", ""); _textView.SetVisibleLineCount(2); _vimBuffer.ProcessNotation("V"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); Assert.Equal(_textBuffer.GetLineRange(0).ExtentIncludingLineBreak, _textView.GetSelectionSpan()); var point = _textView.GetPointInLine(1, 5); // 'o' in 'horse' _testableMouseDevice.Point = point; _vimBuffer.ProcessNotation("<S-LeftMouse>"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); Assert.Equal(_textBuffer.GetLineRange(0, 1).ExtentIncludingLineBreak, _textView.GetSelectionSpan()); Assert.Equal(point.Position, _textView.GetCaretPoint().Position); } [WpfFact] public void ExclusiveDoubleClick() { Create("cat dog bear", ""); _textView.SetVisibleLineCount(2); _globalSettings.Selection = "exclusive"; var point = _textView.GetPointInLine(0, 5); // 'o' in 'dog' _testableMouseDevice.Point = point; _vimBuffer.ProcessNotation("<LeftMouse><2-LeftMouse>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(7, _textView.GetCaretPoint().Position); // ' ' after 'dog' } [WpfFact] public void InclusiveDoubleClick() { Create("cat dog bear", ""); _textView.SetVisibleLineCount(2); _globalSettings.Selection = "inclusive"; var point = _textView.GetPointInLine(0, 5); // 'o' in 'dog' _testableMouseDevice.Point = point; _vimBuffer.ProcessNotation("<LeftMouse><2-LeftMouse>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(6, _textView.GetCaretPoint().Position); // 'g' in 'dog' } [WpfFact] public void ExclusiveDoubleClickAndDrag() { Create("cat dog bear bat", ""); _textView.SetVisibleLineCount(2); _globalSettings.Selection = "exclusive"; _testableMouseDevice.Point = _textView.GetPointInLine(0, 5); // 'o' in 'dog' _vimBuffer.ProcessNotation("<LeftMouse><LeftRelease><2-LeftMouse>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(7, _textView.GetCaretPoint().Position); // ' ' after 'dog' _testableMouseDevice.Point = _textView.GetPointInLine(0, 9); // 'e' in 'bear' _vimBuffer.ProcessNotation("<LeftDrag>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog bear", _textView.GetSelectionSpan().GetText()); Assert.Equal(12, _textView.GetCaretPoint().Position); // ' ' after 'bear' _testableMouseDevice.Point = _textView.GetPointInLine(0, 1); // 'a' in 'cat' _vimBuffer.ProcessNotation("<LeftDrag>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("cat ", _textView.GetSelectionSpan().GetText()); Assert.Equal(0, _textView.GetCaretPoint().Position); // 'c' in 'cat' _testableMouseDevice.Point = _textView.GetPointInLine(0, 9); // 'e' in 'bear' _vimBuffer.ProcessNotation("<LeftRelease>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog bear", _textView.GetSelectionSpan().GetText()); Assert.Equal(12, _textView.GetCaretPoint().Position); // ' ' after 'bear' } [WpfFact] public void InclusiveDoubleClickAndDrag() { Create("cat dog bear bat", ""); _textView.SetVisibleLineCount(2); _globalSettings.Selection = "inclusive"; _testableMouseDevice.Point = _textView.GetPointInLine(0, 5); // 'o' in 'dog' _vimBuffer.ProcessNotation("<LeftMouse><LeftRelease><2-LeftMouse>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(6, _textView.GetCaretPoint().Position); // 'g' in 'dog' _testableMouseDevice.Point = _textView.GetPointInLine(0, 9); // 'e' in 'bear' _vimBuffer.ProcessNotation("<LeftDrag>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog bear", _textView.GetSelectionSpan().GetText()); Assert.Equal(11, _textView.GetCaretPoint().Position); // 'r' in 'bear' _testableMouseDevice.Point = _textView.GetPointInLine(0, 1); // 'a' in 'cat' _vimBuffer.ProcessNotation("<LeftDrag>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("cat dog", _textView.GetSelectionSpan().GetText()); Assert.Equal(0, _textView.GetCaretPoint().Position); // 'c' in 'cat' _testableMouseDevice.Point = _textView.GetPointInLine(0, 9); // 'e' in 'bear' _vimBuffer.ProcessNotation("<LeftRelease>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("dog bear", _textView.GetSelectionSpan().GetText()); Assert.Equal(11, _textView.GetCaretPoint().Position); // 'r' in 'bear' } [WpfFact] public void TokenDoubleClick() { Create("cat (dog) bear", ""); _textView.SetVisibleLineCount(2); _globalSettings.Selection = "inclusive"; var point = _textView.GetPointInLine(0, 4); // open paren _testableMouseDevice.Point = point; _vimBuffer.ProcessNotation("<LeftMouse><LeftRelease><2-LeftMouse><LeftRelease>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("(dog)", _textView.GetSelectionSpan().GetText()); Assert.Equal(8, _textView.GetCaretPoint().Position); // close paren } [WpfFact] public void DirectiveDoubleClick() { Create("cat", "#if DEBUG", "xyzzy", "#endif", "dog", ""); _textView.SetVisibleLineCount(6); _globalSettings.Selection = "inclusive"; var startPoint = _textView.GetPointInLine(1, 0); // '#' in '#if' _testableMouseDevice.Point = startPoint; _vimBuffer.ProcessNotation("<LeftMouse><LeftRelease><2-LeftMouse><LeftRelease>"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); var range = SnapshotLineRange.CreateForLineNumberRange(_textView.TextSnapshot, 1, 3); Assert.Equal(range.Value.ExtentIncludingLineBreak, _textView.GetSelectionSpan()); var endPoint = _textView.GetPointInLine(3, 0); // '#' in '#endif' Assert.Equal(endPoint.Position, _textView.GetCaretPoint().Position); } [WpfFact] public void TripleClick() { Create("cat dog bear", "pig horse bat", ""); _textView.SetVisibleLineCount(3); var point = _textView.GetPointInLine(1, 5); // 'o' in 'horse' _testableMouseDevice.Point = point; _vimBuffer.ProcessNotation("<LeftMouse><LeftRelease><2-LeftMouse><LeftRelease><3-LeftMouse><LeftRelease>"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); Assert.Equal(_textBuffer.GetLineRange(1).ExtentIncludingLineBreak, _textView.GetSelectionSpan()); Assert.Equal(point.Position, _textView.GetCaretPoint().Position); } [WpfFact] public void QuadrupleClick() { Create("cat dog bear", ""); _textView.SetVisibleLineCount(2); var point = _textView.GetPointInLine(0, 5); // 'o' in 'dog' _testableMouseDevice.Point = point; _vimBuffer.ProcessNotation("<LeftMouse><LeftRelease><2-LeftMouse><LeftRelease><3-LeftMouse><LeftRelease><4-LeftMouse><LeftRelease>"); Assert.Equal(ModeKind.VisualBlock, _vimBuffer.ModeKind); Assert.Equal("o", _textView.GetSelectionSpan().GetText()); Assert.Equal(point.Position, _textView.GetCaretPoint().Position); } } /// <summary> /// Standard block selection tests /// </summary> public abstract class BlockSelectionTest : VisualModeIntegrationTest { private int _tabStop; protected override void Create(params string[] lines) { base.Create(lines); _tabStop = _vimBuffer.LocalSettings.TabStop; } public sealed class TabTest : BlockSelectionTest { protected override void Create(params string[] lines) { base.Create(); UpdateTabStop(_vimBuffer, 4); _vimBuffer.TextView.SetText(lines); _textView.MoveCaretTo(0); } [WpfFact] public void CaretInTab() { Create("cat", "\tdog"); _vimBuffer.ProcessNotation("<C-Q>j"); Assert.Equal( new[] { _textBuffer.GetLineSpan(0, 3), _textBuffer.GetLineSpan(1, 1) }, _textView.Selection.SelectedSpans); } [WpfFact] public void CaretInTabAnchorNonZero() { Create("cat", "\tdog"); _vimBuffer.ProcessNotation("ll<C-Q>j"); Assert.Equal( new[] { _textBuffer.GetLineSpan(0, 3), _textBuffer.GetLineSpan(1, 1) }, _textView.Selection.SelectedSpans); } /// <summary> /// The caret is past the tab. Hence the selection for the first line should /// be correct. /// </summary> [WpfFact] public void CaretPastTab() { Create("kitty", "\tdog"); _vimBuffer.ProcessNotation("ll<C-Q>jl"); // In a strict vim interpretation both '\t' and 'd' would be selected in the // second line. The Visual Studio editor won't have this selection and instead // will not select the tab since it's only partially selected. Hence only the // 'd' will end up selected Assert.Equal( new[] { _textBuffer.GetLineSpan(0, 2, 3), _textBuffer.GetLineSpan(1, 1, 1) }, _textView.Selection.SelectedSpans); } /// <summary> /// This is an anti fact /// /// The WPF editor can't place the caret in the middle of a tab. It can't /// for example put it on the 2 of the 4th space a tab occupies. /// </summary> [WpfFact] public void MiddleOfTab() { Create("cat", "d\tog"); _vimBuffer.LocalSettings.TabStop = 4; _vimBuffer.ProcessNotation("ll<C-q>jl"); var textView = _vimBuffer.TextView; Assert.Equal('t', textView.Selection.Start.Position.GetChar()); Assert.Equal('g', textView.Selection.End.Position.GetChar()); } } public sealed class MiscTest : BlockSelectionTest { /// <summary> /// Make sure the CTRL-Q command causes the block selection to start out as a single width /// column /// </summary> [WpfFact] public void InitialState() { Create("hello world"); _vimBuffer.ProcessNotation("<C-Q>"); Assert.Equal(ModeKind.VisualBlock, _vimBuffer.ModeKind); var blockSpan = new BlockSpan(_textBuffer.GetPoint(0), tabStop: _tabStop, spaces: 1, height: 1); Assert.Equal(blockSpan, _vimBuffer.GetSelectionBlockSpan()); } /// <summary> /// Make sure the CTRL-Q command causes the block selection to start out as a single width /// column from places other than the start of the document /// </summary> [WpfFact] public void InitialNonStartPoint() { Create("big cats", "big dogs", "big trees"); var point = _textBuffer.GetPointInLine(1, 3); _textView.MoveCaretTo(point); _vimBuffer.ProcessNotation("<C-Q>"); Assert.Equal(ModeKind.VisualBlock, _vimBuffer.ModeKind); var blockSpan = new BlockSpan(point, tabStop: _tabStop, spaces: 1, height: 1); Assert.Equal(blockSpan, _vimBuffer.GetSelectionBlockSpan()); } /// <summary> /// A left movement in block selection should move the selection to the left /// </summary> [WpfFact] public void Backwards() { Create("big cats", "big dogs"); _textView.MoveCaretTo(2); _vimBuffer.ProcessNotation("<C-Q>jh"); Assert.Equal(ModeKind.VisualBlock, _vimBuffer.ModeKind); var blockSpan = new BlockSpan(_textView.GetPoint(1), tabStop: _tabStop, spaces: 2, height: 2); Assert.Equal(blockSpan, _vimBuffer.GetSelectionBlockSpan()); } /// <summary> /// A delete in end-of-line block mode should delete to the /// end of all lines /// </summary> [WpfFact] public void DeleteToEndOfLine() { Create("abc def ghi", "jkl mno", "pqr", ""); _vimBuffer.ProcessNotation("2l<C-Q>2j$d"); Assert.Equal(new[] { "ab", "jk", "pq", "" }, _textBuffer.GetLines()); } /// <summary> /// Block put should work even when using the clipboard as the /// unnamed register /// </summary> [WpfTheory] [InlineData("")] [InlineData("unnamed")] public void DeleteAndPut(string clipboard) { // Reported in issue #2694. Create("abc def ghi jkl", "mno pqr stu vwx", ""); _globalSettings.Clipboard = clipboard; _textView.MoveCaretToLine(0, 4); _vimBuffer.ProcessNotation("<C-Q>jeldwP"); Assert.Equal(new[] { "abc ghi def jkl", "mno stu pqr vwx", "" }, _textBuffer.GetLines()); } } public sealed class ExclusiveTest : BlockSelectionTest { /// <summary> /// When selection is exclusive there should still be a single column selected in block /// mode even if the original width is 1 /// </summary> [WpfFact] public void OneWidthBlock() { Create("the dog", "the cat"); _textView.MoveCaretTo(1); _globalSettings.Selection = "exclusive"; _vimBuffer.Process(KeyInputUtil.CharWithControlToKeyInput('q')); _vimBuffer.Process('j'); var blockSpan = _textBuffer.GetBlockSpan(1, 1, 0, 2, tabStop: _tabStop); Assert.Equal(blockSpan, _vimBuffer.GetSelectionBlockSpan()); Assert.Equal(_textView.GetPointInLine(1, 1), _textView.GetCaretPoint()); } /// <summary> /// When selection is exclusive block selection should shrink by one in width /// </summary> [WpfFact] public void TwoWidthBlock() { Create("the dog", "the cat"); _textView.MoveCaretTo(1); _globalSettings.Selection = "exclusive"; _vimBuffer.Process(KeyInputUtil.CharWithControlToKeyInput('q')); _vimBuffer.Process("jl"); var blockSpan = _textBuffer.GetBlockSpan(1, 1, 0, 2, tabStop: _tabStop); Assert.Equal(blockSpan, _vimBuffer.GetSelectionBlockSpan()); Assert.Equal(_textView.GetPointInLine(1, 2), _textView.GetCaretPoint()); } } public sealed class VirtualEditTest : BlockSelectionTest { protected override void Create(params string[] lines) { base.Create(lines); _globalSettings.VirtualEdit = "block"; } [WpfFact] public void Inclusive() { Create("cat", "dog bear", "tree", ""); _globalSettings.Selection = "inclusive"; _vimBuffer.ProcessNotation("<C-q>2j8l"); Assert.Equal(_textBuffer.GetVirtualPointInLine(2, 4, 4), _textView.GetCaretVirtualPoint()); var blockSpan = _vimBuffer.GetSelectionBlockSpan(); Assert.Equal(3, blockSpan.Height); Assert.Equal(9, blockSpan.SpacesLength); } [WpfFact] public void Exclusive() { Create("cat", "dog bear", "tree", ""); _globalSettings.Selection = "exclusive"; _vimBuffer.ProcessNotation("<C-q>2j8l"); Assert.Equal(_textBuffer.GetVirtualPointInLine(2, 4, 4), _textView.GetCaretVirtualPoint()); var blockSpan = _vimBuffer.GetSelectionBlockSpan(); Assert.Equal(3, blockSpan.Height); Assert.Equal(8, blockSpan.SpacesLength); } } } public sealed class AddSubtractTest : VisualModeIntegrationTest { [WpfTheory] [InlineData("v")] [InlineData("V")] [InlineData("<C-v>")] public void Basic(string visualKey) { - Create("1", "2", "3", ""); + Create("1", "2", "", "3", ""); _vimBuffer.ProcessNotation(visualKey); - _vimBuffer.ProcessNotation("2j$"); + _vimBuffer.ProcessNotation("3j$"); _vimBuffer.ProcessNotation("<C-a>"); - Assert.Equal(new[] { "2", "3", "4", "" }, _textBuffer.GetLines()); + Assert.Equal(new[] { "2", "3", "", "4", "" }, _textBuffer.GetLines()); } [WpfTheory] [InlineData("v")] [InlineData("V")] [InlineData("<C-v>")] public void Progressive(string visualKey) { - Create("1", "2", "3", ""); + Create("1", "2", "", "3", ""); _vimBuffer.ProcessNotation(visualKey); - _vimBuffer.ProcessNotation("2j$"); + _vimBuffer.ProcessNotation("3j$"); _vimBuffer.ProcessNotation("g<C-a>"); - Assert.Equal(new[] { "2", "4", "6", "" }, _textBuffer.GetLines()); + Assert.Equal(new[] { "2", "4", "", "6", "" }, _textBuffer.GetLines()); } } public abstract class VisualShiftTest : VisualModeIntegrationTest { protected abstract string Select { get; } protected abstract IEnumerable<string> Lines(); [WpfFact] public void IndentAdds() { Create("one", "two", "three"); _vimBuffer.ProcessNotation($"{Select}>"); Assert.All(Lines(), line => Assert.StartsWith("\t", line)); } [WpfFact] public void OutdentRemoves() { Create("\tone", "\ttwo", "\tthree"); _vimBuffer.ProcessNotation($"{Select}<lt>"); Assert.All(Lines(), line => Assert.False(line.StartsWith("\t"))); } public sealed class Block : VisualShiftTest { protected override string Select => "<C-Q>jj"; protected override IEnumerable<string> Lines() => _textBuffer.GetLines(); } public sealed class Line : VisualShiftTest { protected override string Select => "Vj"; protected override IEnumerable<string> Lines() => _textBuffer.GetLines().Take(2); } public sealed class Character : VisualShiftTest { protected override string Select => "v"; protected override IEnumerable<string> Lines() => _textBuffer.GetLines().Take(1); } } public sealed class ChangeLineSelectionTest : VisualModeIntegrationTest { /// <summary> /// Even a visual character change is still a linewise delete /// </summary> [WpfFact] public void CharacterIsLineWise() { Create("cat", "dog"); _vimBuffer.Process("vC"); Assert.Equal("cat" + Environment.NewLine, UnnamedRegister.StringValue); Assert.Equal(new[] { "", "dog" }, _textBuffer.GetLines()); } [WpfFact] public void LineIsLineWise() { Create("cat", "dog"); _vimBuffer.Process("VC"); Assert.Equal("cat" + Environment.NewLine, UnnamedRegister.StringValue); Assert.Equal(new[] { "", "dog" }, _textBuffer.GetLines()); } } public abstract class EnterVisualModeWithCountTest : VisualModeIntegrationTest { public sealed class CharacterTest : EnterVisualModeWithCountTest { [WpfTheory] [InlineData('v')] [InlineData('V')] public void SimpleCharacter(char kind) { Create("dog"); _vimBuffer.ProcessNotation("vy"); Assert.Equal(StoredVisualSelection.NewCharacter(width: 1), VimData.LastVisualSelection.Value); _vimBuffer.ProcessNotation($"2{kind}"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal("do", _textView.Selection.GetSpan().GetText()); } [WpfTheory] [InlineData('v')] [InlineData('V')] public void CountGoesPastSingleLine(char kind) { Create("dog", ""); _vimBuffer.ProcessNotation("vly"); Assert.Equal(StoredVisualSelection.NewCharacter(width: 2), VimData.LastVisualSelection.Value); _vimBuffer.ProcessNotation($"20{kind}"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); _vimBuffer.ProcessNotation("y"); Assert.Equal("dog" + Environment.NewLine, UnnamedRegister.StringValue); } [WpfTheory] [InlineData('v')] [InlineData('V')] public void CountAcrossLines(char kind) { Create("dog", "cat", "fish", "tree"); _vimBuffer.ProcessNotation("vjy"); Assert.Equal(StoredVisualSelection.NewCharacterLine(lineCount: 2, lastLineMaxOffset: 0), VimData.LastVisualSelection.Value); _vimBuffer.ProcessNotation($"2{kind}"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal(_textBuffer.GetPoint(0), _textView.Selection.Start.Position); Assert.Equal(_textBuffer.GetPointInLine(line: 3, column: 1), _textView.Selection.End.Position); } /// <summary> /// When using a count across a multi-line character selection the count just multilies lines /// but keeps the character in the same column. /// </summary> [WpfTheory] [InlineData('v')] [InlineData('V')] public void CountAcrossLinesNonZeroColumn(char kind) { Create("dog", "cat", "fish", "tree"); _vimBuffer.ProcessNotation("lvjy"); Assert.Equal(StoredVisualSelection.NewCharacterLine(lineCount: 2, lastLineMaxOffset: 0), VimData.LastVisualSelection.Value); _vimBuffer.ProcessNotation($"2{kind}"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal(_textBuffer.GetPointInLine(line: 0, column: 1), _textView.Selection.Start.Position); Assert.Equal(_textBuffer.GetPointInLine(line: 3, column: 2), _textView.Selection.End.Position); } /// <summary> /// The 3rd column doesn't exist here but should go to the 2nd which is the /// new line /// </summary> [WpfTheory] [InlineData('v')] [InlineData('V')] public void CountAcrossLinesNonZeroColumnThatExtends(char kind) { Create("dog", "cat", "fish", "t"); _vimBuffer.ProcessNotation("llvjy"); Assert.Equal(StoredVisualSelection.NewCharacterLine(lineCount: 2, lastLineMaxOffset: 0), VimData.LastVisualSelection.Value); _vimBuffer.ProcessNotation($"2{kind}"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal(_textBuffer.GetPointInLine(line: 0, column: 2), _textView.Selection.Start.Position); Assert.Equal(_textBuffer.GetPointInLine(line: 3, column: 1), _textView.Selection.End.Position); } /// <summary> /// When looking at a multiline character span the last column is stored as an offset of the /// start point: positive or negative. In the case where the 1v command results in a single line /// this will result in a reverse selection. /// </summary> [WpfTheory] [InlineData('v')] [InlineData('V')] public void MultipleLinesShrunkResultsInReverseSpan(char kind) { Create("dog", "cat", "fish", "tt"); _vimBuffer.ProcessNotation("llvjhy"); Assert.Equal(StoredVisualSelection.NewCharacterLine(lineCount: 2, lastLineMaxOffset: -1), VimData.LastVisualSelection.Value); _textView.MoveCaretToLine(lineNumber: 3, column: 2); _vimBuffer.ProcessNotation($"1{kind}"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal(_textBuffer.GetPointInLine(line: 3, column: 1), _textView.Selection.Start.Position); Assert.Equal(_textBuffer.GetPointInLine(line: 3, column: 2), _textView.Selection.End.Position); } } public sealed class LineTest : EnterVisualModeWithCountTest { [WpfTheory] [InlineData('v')] [InlineData('V')] public void SimpleLine(char kind) { Create("dog", "cat", "fish", "tree"); _vimBuffer.ProcessNotation("Vy"); Assert.Equal(StoredVisualSelection.NewLine(1), VimData.LastVisualSelection.Value); _vimBuffer.ProcessNotation($"1{kind}"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); var selection = _vimBuffer.VisualLineMode.VisualSelection; var range = selection.AsLine().LineRange; Assert.Equal(range, _textBuffer.GetLineRange(startLine: 0, endLine: 0)); } [WpfTheory] [InlineData('v')] [InlineData('V')] public void SimpleLineDoubleCount(char kind) { Create("dog", "cat", "fish", "tree"); _vimBuffer.ProcessNotation("Vy"); Assert.Equal(StoredVisualSelection.NewLine(1), VimData.LastVisualSelection.Value); _vimBuffer.ProcessNotation($"2{kind}"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); var selection = _vimBuffer.VisualLineMode.VisualSelection; var range = selection.AsLine().LineRange; Assert.Equal(range, _textBuffer.GetLineRange(startLine: 0, endLine: 1)); } } } public sealed class DeleteLineSelectionTest : VisualModeIntegrationTest { /// <summary> /// Even a visual character change is still a linewise delete /// </summary> [WpfFact] public void CharacterIsLineWise() { Create("cat", "dog"); _vimBuffer.Process("vD"); Assert.Equal("cat" + Environment.NewLine, UnnamedRegister.StringValue); Assert.Equal(new[] { "dog" }, _textBuffer.GetLines()); } [WpfFact] public void LineIsLineWise() { Create("cat", "dog"); _vimBuffer.Process("VD"); Assert.Equal("cat" + Environment.NewLine, UnnamedRegister.StringValue); Assert.Equal(new[] { "dog" }, _textBuffer.GetLines()); } } public abstract class DeleteSelectionTest : VisualModeIntegrationTest { public sealed class CharacterTest : DeleteSelectionTest { /// <summary> /// When an entire line is selected in character wise mode and then deleted /// it should not be a line delete but instead delete the contents of the /// line. /// </summary> [WpfFact] public void LineContents() { Create("cat", "dog"); EnterMode(ModeKind.VisualCharacter, _textView.GetLineSpan(0, 3)); _vimBuffer.Process("x"); Assert.Equal("", _textView.GetLine(0).GetText()); Assert.Equal("dog", _textView.GetLine(1).GetText()); } /// <summary> /// If the character wise selection extents into the line break then the /// entire line should be deleted /// </summary> [WpfFact] public void LineContentsFromBreak() { Create("cat", "dog"); _globalSettings.VirtualEdit = "onemore"; EnterMode(ModeKind.VisualCharacter, _textView.GetLine(0).ExtentIncludingLineBreak); _vimBuffer.Process("x"); Assert.Equal("dog", _textView.GetLine(0).GetText()); } [WpfFact] public void Issue1507() { Create("cat", "dog", "fish"); _textView.MoveCaretTo(1); _vimBuffer.Process("vjllx"); Assert.Equal(new[] { "cfish" }, _textBuffer.GetLines()); } } public sealed class LineTest : DeleteSelectionTest { /// <summary> /// Deleting to the end of the file should move the caret up /// </summary> [WpfFact] public void DeleteLines_ToEndOfFile() { // Reported in issue #2477. Create("cat", "dog", "fish", ""); _textView.MoveCaretToLine(1, 0); _vimBuffer.Process("VGd"); Assert.Equal(new[] { "cat", "" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetPointInLine(0, 0), _textView.GetCaretPoint()); } /// <summary> /// Deleting lines should obey the 'startofline' setting /// </summary> [WpfFact] public void DeleteLines_StartOfLine() { // Reported in issue #2477. Create(" cat", " dog", " fish", ""); _textView.MoveCaretToLine(1, 2); _vimBuffer.Process("Vd"); Assert.Equal(new[] { " cat", " fish", "" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetPointInLine(1, 1), _textView.GetCaretPoint()); } /// <summary> /// Deleting lines should preserve spaces to caret when /// 'nostartofline' is in effect /// </summary> [WpfFact] public void DeleteLines_NoStartOfLine() { // Reported in issue #2477. Create(" cat", " dog", " fish", ""); _globalSettings.StartOfLine = false; _textView.MoveCaretToLine(1, 2); _vimBuffer.Process("Vd"); Assert.Equal(new[] { " cat", " fish", "" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetPointInLine(1, 2), _textView.GetCaretPoint()); } /// <summary> /// Undoing a visual line delete should return the caret to the first line /// </summary> [WpfFact] public void DeleteLines_Undo() { // Reported in issue #2477. Create("cat", "dog", "fish", "bear", ""); _textView.MoveCaretToLine(1, 0); _vimBuffer.Process("Vj"); Assert.Equal(_textView.GetPointInLine(2, 0), _textView.GetCaretPoint()); _vimBuffer.Process("d"); Assert.Equal(new[] { "cat", "bear", "" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetPointInLine(1, 0), _textView.GetCaretPoint()); _vimBuffer.Process("u"); Assert.Equal(new[] { "cat", "dog", "fish", "bear", "" }, _textBuffer.GetLines()); Assert.Equal(_textView.GetPointInLine(1, 0), _textView.GetCaretPoint()); } } public sealed class BlockTest : DeleteSelectionTest { [WpfFact] public void Simple() { Create(4, "cat", "dog", "fish"); _vimBuffer.ProcessNotation("<C-q>jjx"); Assert.Equal(new[] { "at", "og", "ish" }, _textBuffer.GetLines()); } [WpfFact] public void PartialTab() { Create(4, "cat", "\tdog", "fish"); _vimBuffer.ProcessNotation("<C-q>jjx"); Assert.Equal(new[] { "at", " dog", "ish" }, _textBuffer.GetLines()); } } public sealed class MiscTest : DeleteSelectionTest { /// <summary> /// The 'e' motion should result in a selection that encompasses the entire word /// </summary> [WpfFact] public void EndOfWord() { Create("the dog. cat"); _textView.MoveCaretTo(4); _vimBuffer.Process("vex"); Assert.Equal("dog", UnnamedRegister.StringValue); Assert.Equal(4, _textView.GetCaretPoint().Position); } /// <summary> /// The 'e' motion should result in a selection that encompasses the entire word /// </summary> [WpfFact] public void EndOfWord_Block() { Create("the dog. end", "the cat. end", "the fish. end"); _textView.MoveCaretTo(4); _vimBuffer.Process(KeyInputUtil.CharWithControlToKeyInput('q')); _vimBuffer.Process("jex"); Assert.Equal("the . end", _textBuffer.GetLine(0).GetText()); Assert.Equal("the . end", _textBuffer.GetLine(1).GetText()); Assert.Equal("the fish. end", _textBuffer.GetLine(2).GetText()); } /// <summary> /// The 'w' motion should result in a selection that encompasses the entire word /// </summary> [WpfFact] public void Word() { Create("the dog. cat"); _textView.MoveCaretTo(4); _vimBuffer.Process("vwx"); Assert.Equal("dog.", UnnamedRegister.StringValue); Assert.Equal(4, _textView.GetCaretPoint().Position); } /// <summary> /// The 'e' motion should select up to and including the end of the word /// /// https://github.com/VsVim/VsVim/issues/568 /// </summary> [WpfFact] public void EndOfWordMotion() { Create("ThisIsALongWord. ThisIsAnotherLongWord!"); _vimBuffer.Process("vex"); Assert.Equal(". ThisIsAnotherLongWord!", _textBuffer.GetLine(0).GetText()); } } } public sealed class InclusiveSelection : VisualModeIntegrationTest { protected override void Create(params string[] lines) { base.Create(lines); _globalSettings.Selection = "inclusive"; } /// <summary> /// The $ movement should put the caret past the end of the line /// </summary> [WpfFact] public void MoveEndOfLine_Dollar() { Create("cat", "dog"); _vimBuffer.Process("v$"); Assert.Equal(3, _textView.GetCaretPoint().Position); } } public sealed class ExclusiveSelection : VisualModeIntegrationTest { protected override void Create(params string[] lines) { base.Create(lines); _globalSettings.Selection = "exclusive"; } /// <summary> /// The caret position should be on the next character for a move right /// </summary> [WpfFact] public void CaretPosition_Right() { Create("the dog"); _vimBuffer.Process("vl"); _vimBuffer.Process(VimKey.Escape); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// The caret position should be on the start of the next word after leaving visual mode /// </summary> [WpfFact] public void CaretPosition_Word() { Create("the dog"); _vimBuffer.Process("vw"); _vimBuffer.Process(VimKey.Escape); Assert.Equal(4, _textView.GetCaretPoint().Position); } /// <summary> /// Make sure the 'e' motion still goes one character extra during a line wise movement /// </summary> [WpfFact] public void CaretPosition_EndOfWordLineWise() { Create("the dog. the cat"); _textView.MoveCaretTo(4); _vimBuffer.Process("Ve"); Assert.Equal(7, _textView.GetCaretPoint().Position); } /// <summary> /// The $ movement should put the caret past the end of the line /// </summary> [WpfFact] public void MoveEndOfLine_Dollar() { Create("cat", "dog"); _vimBuffer.Process("v$"); Assert.Equal(3, _textView.GetCaretPoint().Position); } /// <summary> /// The 'l' movement should put the caret past the end of the line /// </summary> [WpfFact] public void MoveEndOfLine_Right() { Create("cat", "dog"); _vimBuffer.Process("vlll"); Assert.Equal(3, _textView.GetCaretPoint().Position);
VsVim/VsVim
54b67c09437b6ef10a27892c54b7f10e4dddee08
Fix UI delay in navigate to
diff --git a/Src/VsVimShared/Implementation/Misc/StandardCommandTarget.cs b/Src/VsVimShared/Implementation/Misc/StandardCommandTarget.cs index 2b81a21..f18633f 100644 --- a/Src/VsVimShared/Implementation/Misc/StandardCommandTarget.cs +++ b/Src/VsVimShared/Implementation/Misc/StandardCommandTarget.cs @@ -1,451 +1,451 @@ using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Windows; using System.Windows.Input; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; using Vim; using Vim.Extensions; namespace Vim.VisualStudio.Implementation.Misc { internal sealed class StandardCommandTarget : ICommandTarget { private readonly IVimBuffer _vimBuffer; private readonly IVimBufferCoordinator _vimBufferCoordinator; private readonly ITextBuffer _textBuffer; private readonly ITextView _textView; private readonly ITextManager _textManager; private readonly ICommonOperations _commonOperations; private readonly IDisplayWindowBroker _broker; private readonly IOleCommandTarget _nextOleCommandTarget; private static readonly Dictionary<KeyInput, Key> s_wpfKeyMap; internal StandardCommandTarget( IVimBufferCoordinator vimBufferCoordinator, ITextManager textManager, ICommonOperations commonOperations, IDisplayWindowBroker broker, IOleCommandTarget nextOleCommandTarget) { _vimBuffer = vimBufferCoordinator.VimBuffer; _vimBufferCoordinator = vimBufferCoordinator; _textBuffer = _vimBuffer.TextBuffer; _textView = _vimBuffer.TextView; _textManager = textManager; _commonOperations = commonOperations; _broker = broker; _nextOleCommandTarget = nextOleCommandTarget; } static StandardCommandTarget() { s_wpfKeyMap = new Dictionary<KeyInput, Key> { { KeyInputUtil.VimKeyToKeyInput(VimKey.Back), Key.Back }, { KeyInputUtil.VimKeyToKeyInput(VimKey.Up), Key.Up }, { KeyInputUtil.VimKeyToKeyInput(VimKey.Down), Key.Down }, { KeyInputUtil.VimKeyToKeyInput(VimKey.Left), Key.Left }, { KeyInputUtil.VimKeyToKeyInput(VimKey.Right), Key.Right }, { KeyInputUtil.VimKeyToKeyInput(VimKey.Home), Key.Home }, { KeyInputUtil.VimKeyToKeyInput(VimKey.End), Key.End }, { KeyInputUtil.VimKeyToKeyInput(VimKey.Delete), Key.Delete }, }; } /// <summary> /// Try and map a KeyInput to a single KeyInput value. This will only succeed for KeyInput /// values which have no mapping or map to a single KeyInput value /// </summary> private bool TryGetSingleMapping(KeyInput original, out KeyInput mapped) { var result = _vimBuffer.GetKeyInputMapping(original); if (result.IsNeedsMoreInput || result.IsRecursive || result.IsPartiallyMapped) { // No single mapping mapped = null; return false; } if (result.IsMapped || result.IsUnmapped) { var set = result.IsMapped ? ((KeyMappingResult.Mapped)result).KeyInputSet : ((KeyMappingResult.Unmapped)result).KeyInputSet; if (set.Length != 1) { mapped = null; return false; } mapped = set.FirstKeyInput.Value; return true; } // Shouldn't get here because all cases of KeyMappingResult should be // handled above Contract.Assert(false); mapped = null; return false; } /// <summary> /// Is this KeyInput intended to be processed by the active display window /// </summary> private bool IsDisplayWindowKey(KeyInput keyInput) { // Consider normal completion if (_broker.IsCompletionActive) { return keyInput.IsArrowKey || keyInput == KeyInputUtil.EnterKey || keyInput == KeyInputUtil.TabKey || keyInput.Key == VimKey.Back; } if (_broker.IsSignatureHelpActive) { return keyInput.IsArrowKey; } return false; } /// <summary> /// Try and process the KeyInput from the Exec method. This method decides whether or not /// a key should be processed directly by IVimBuffer or if should be going through /// IOleCommandTarget. Generally the key is processed by IVimBuffer but for many intellisense /// scenarios we want the key to be routed to Visual Studio directly. Issues to consider /// here are ... /// /// - How should the KeyInput participate in Macro playback? /// - Does both VsVim and Visual Studio need to process the key (Escape mainly) /// /// </summary> private bool TryProcessWithBuffer(KeyInput keyInput) { // If, for some reason, keyboard input is being routed to the text // view but it isn't focused, focus it here. void CheckFocus() { if (_vimBuffer.TextView is IWpfTextView wpfTextView && !wpfTextView.VisualElement.IsFocused) { VimTrace.TraceError("forcing focus back to text view"); wpfTextView.VisualElement.Focus(); } } // If the IVimBuffer can't process it then it doesn't matter if (!_vimBuffer.CanProcess(keyInput)) { return false; } // In the middle of a word completion session let insert mode handle the input. It's // displaying the intellisense itself and this method is meant to let custom intellisense // operate normally if (_vimBuffer.ModeKind == ModeKind.Insert && _vimBuffer.InsertMode.ActiveWordCompletionSession.IsSome()) { return _vimBuffer.Process(keyInput).IsAnyHandled; } // If we are in a peek definition window and normal mode we need to let the Escape key // pass on to the next command target. This is necessary to close the peek definition // window if (_vimBuffer.ModeKind == ModeKind.Normal && _textView.IsPeekView() && keyInput == KeyInputUtil.EscapeKey) { return false; } // If we are in a peek defintion window and in command mode, the // command margin text box won't receive certain keys like // backspace as it normally would. Work around this problem by // generating WPF key events for keys that we know should go to the // command margin text box. Reported in issue #2492. if (_vimBuffer.ModeKind == ModeKind.Command && _textView.IsPeekView() && TryProcessWithWpf(keyInput)) { return true; } // The only time we actively intercept keys and route them through IOleCommandTarget // is when one of the IDisplayWindowBroker windows is active // // In those cases if the KeyInput is a command which should be handled by the // display window we route it through IOleCommandTarget to get the proper // experience for those features if (!_broker.IsAnyDisplayActive()) { CheckFocus(); return _vimBuffer.Process(keyInput).IsAnyHandled; } // Next we need to consider here are Key mappings. The CanProcess and Process APIs // will automatically map the KeyInput under the hood at the IVimBuffer level but // not at the individual IMode. Have to manually map here and test against the // mapped KeyInput if (!TryGetSingleMapping(keyInput, out KeyInput mapped)) { return _vimBuffer.Process(keyInput).IsAnyHandled; } bool handled; if (IsDisplayWindowKey(mapped)) { // If the key which actually needs to be processed is a display window key, say // down, up, etc..., then forward it on to the next IOleCommandTarget. It is responsible // for mapping that key to action against the display window handled = ErrorHandler.Succeeded(_nextOleCommandTarget.Exec(mapped)); } else { CheckFocus(); // Intentionally using keyInput here and not mapped. Process will do mapping on the // provided input hence we should be using the original keyInput here not mapped handled = _vimBuffer.Process(keyInput).IsAnyHandled; } // The Escape key should always dismiss the active completion session. However Vim // itself is mostly ignorant of display windows and typically won't dismiss them // as part of processing Escape (one exception is insert mode). Dismiss it here if // it's still active if (mapped.Key == VimKey.Escape && _broker.IsAnyDisplayActive()) { _broker.DismissDisplayWindows(); } return handled; } /// <summary> /// Try to process the key input with WPF /// </summary> /// <param name="keyInput"></param> /// <returns></returns> private bool TryProcessWithWpf(KeyInput keyInput) { if (s_wpfKeyMap.TryGetValue(keyInput, out Key wpfKey)) { var previewDownHandled = InputManager.Current.ProcessInput( new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, wpfKey) { RoutedEvent = Keyboard.PreviewKeyDownEvent } ); if (previewDownHandled) { return true; } var downHandled = InputManager.Current.ProcessInput( new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, wpfKey) { RoutedEvent = Keyboard.KeyDownEvent } ); return downHandled; } return false; } /// <summary> /// This intercepts the Paste command in Visual Studio and tries to make it work for VsVim. This is /// only possible in a subset of states like command line mode. Otherwise we default to Visual Studio /// behavior /// </summary> private bool Paste() { if (_vimBuffer.ModeKind != ModeKind.Command) { return false; } try { var text = Clipboard.GetText(); var command = _vimBuffer.CommandMode.Command; _vimBuffer.CommandMode.Command = command + text; return true; } catch { return false; } } internal bool Exec(EditCommand editCommand, out Action preAction, out Action postAction) { preAction = null; postAction = null; // If the KeyInput was already handled then pretend we handled it // here. if (editCommand.HasKeyInput && _vimBufferCoordinator.IsDiscarded(editCommand.KeyInput)) { return true; } switch (editCommand.EditCommandKind) { case EditCommandKind.Undo: // The user hit the undo button. Don't attempt to map // anything here and instead just run a single Vim undo // operation _vimBuffer.UndoRedoOperations.Undo(1); return true; case EditCommandKind.Redo: // The user hit the redo button. Don't attempt to map // anything here and instead just run a single Vim redo // operation _vimBuffer.UndoRedoOperations.Redo(1); return true; case EditCommandKind.Paste: return Paste(); case EditCommandKind.GoToDefinition: // The GoToDefinition command will often cause a selection // to occur in the buffer. { - var handler = new UnwantedSelectionHandler(_vimBuffer.Vim, _textManager); + var handler = new UnwantedSelectionHandler(_vimBuffer.Vim); preAction = handler.PreAction; postAction = handler.PostAction; } return false; case EditCommandKind.Comment: case EditCommandKind.Uncomment: // The comment / uncomment command will often induce a // selection on the editor even if there was no selection // before the command was run (single line case). if (_textView.Selection.IsEmpty) { - var handler = new UnwantedSelectionHandler(_vimBuffer.Vim, _textManager); + var handler = new UnwantedSelectionHandler(_vimBuffer.Vim); postAction = () => handler.ClearSelection(_textView); } return false; case EditCommandKind.UserInput: case EditCommandKind.VisualStudioCommand: if (editCommand.HasKeyInput) { var keyInput = editCommand.KeyInput; // Discard the input if it's been flagged by a previous // QueryStatus. if (_vimBufferCoordinator.IsDiscarded(keyInput)) { return true; } // Try and process the command with the IVimBuffer. if (TryProcessWithBuffer(keyInput)) { return true; } // Discard any other unprocessed printable input in // non-input modes. Without this, Visual Studio will // see the command as unhandled and will try to handle // it itself by inserting the character into the // buffer. if (editCommand.EditCommandKind == EditCommandKind.UserInput && CharUtil.IsPrintable(keyInput.Char) && (_vimBuffer.ModeKind == ModeKind.Normal || _vimBuffer.ModeKind.IsAnyVisual())) { _commonOperations.Beep(); return true; } } return false; default: Debug.Assert(false); return false; } } private CommandStatus QueryStatus(EditCommand editCommand) { var action = CommandStatus.PassOn; switch (editCommand.EditCommandKind) { case EditCommandKind.Undo: case EditCommandKind.Redo: action = CommandStatus.Enable; break; case EditCommandKind.Paste: action = _vimBuffer.ModeKind == ModeKind.Command ? CommandStatus.Enable : CommandStatus.PassOn; break; default: if (editCommand.HasKeyInput && _vimBuffer.CanProcess(editCommand.KeyInput)) { action = CommandStatus.Enable; } break; } return action; } #region ICommandTarget CommandStatus ICommandTarget.QueryStatus(EditCommand editCommand) { return QueryStatus(editCommand); } bool ICommandTarget.Exec(EditCommand editCommand, out Action preAction, out Action postAction) { return Exec(editCommand, out preAction, out postAction); } #endregion } [Export(typeof(ICommandTargetFactory))] [Name(VsVimConstants.StandardCommandTargetName)] [Order] internal sealed class StandardCommandTargetFactory : ICommandTargetFactory { private readonly ITextManager _textManager; private readonly ICommonOperationsFactory _commonOperationsFactory; private readonly IDisplayWindowBrokerFactoryService _displayWindowBrokerFactory; [ImportingConstructor] internal StandardCommandTargetFactory( ITextManager textManager, ICommonOperationsFactory commonOperationsFactory, IDisplayWindowBrokerFactoryService displayWindowBrokerFactory) { _textManager = textManager; _commonOperationsFactory = commonOperationsFactory; _displayWindowBrokerFactory = displayWindowBrokerFactory; } ICommandTarget ICommandTargetFactory.CreateCommandTarget(IOleCommandTarget nextCommandTarget, IVimBufferCoordinator vimBufferCoordinator) { var vimBuffer = vimBufferCoordinator.VimBuffer; var displayWindowBroker = _displayWindowBrokerFactory.GetDisplayWindowBroker(vimBuffer.TextView); var commonOperations = _commonOperationsFactory.GetCommonOperations(vimBuffer.VimBufferData); return new StandardCommandTarget(vimBufferCoordinator, _textManager, commonOperations, displayWindowBroker, nextCommandTarget); } } } diff --git a/Src/VsVimShared/Implementation/Misc/UnwantedSelectionHandler.cs b/Src/VsVimShared/Implementation/Misc/UnwantedSelectionHandler.cs index a2356a7..2cfe964 100644 --- a/Src/VsVimShared/Implementation/Misc/UnwantedSelectionHandler.cs +++ b/Src/VsVimShared/Implementation/Misc/UnwantedSelectionHandler.cs @@ -1,74 +1,75 @@ using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Generic; using System.Linq; using Vim.Extensions; namespace Vim.VisualStudio.Implementation.Misc { /// <summary> /// Sometimes performing host actions produces unwanted selections. The /// purpose of this class to detect and remove them. /// </summary> internal sealed class UnwantedSelectionHandler { private readonly IVim _vim; - private readonly ITextManager _textManager; private List<WeakReference<ITextView>> _selected; - internal UnwantedSelectionHandler(IVim vim, ITextManager textManager) + internal UnwantedSelectionHandler(IVim vim) { _vim = vim; - _textManager = textManager; _selected = new List<WeakReference<ITextView>>(); } internal void PreAction() { // Cautiously record which buffers have pre-existing selections. - _selected = _textManager - .GetDocumentTextViews(DocumentLoad.RespectLazy) + _selected = _vim + .VimBuffers + .Select(x => x.TextView) .Where(x => !x.Selection.IsEmpty) .Select(x => new WeakReference<ITextView>(x)) .ToList(); } internal void PostAction() { // Once the host action is stopped, clear out all of the new // selections in active buffers. Leaving the selection puts us // into Visual Mode. Don't force any document loads here. If the // document isn't loaded then it can't have a selection which would // interfere with this. - _textManager.GetDocumentTextViews(DocumentLoad.RespectLazy) + _vim + .VimBuffers + .Select(x => x.TextView) .Where(textView => !textView.Selection.IsEmpty && !HadPreExistingSelection(textView)) .ForEach(textView => ClearSelection(textView)); var focusedWindow = _vim.VimHost.GetFocusedTextView(); if (focusedWindow.IsSome()) { ClearSelection(focusedWindow.Value); } } internal void ClearSelection(ITextView textView) { // Move the caret to the beginning of the selection. var startPoint = textView.Selection.Start; textView.Selection.Clear(); textView.Caret.MoveTo(startPoint); if (_vim.TryGetVimBuffer(textView, out var vimBuffer)) { vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); } } private bool HadPreExistingSelection(ITextView textView) { return _selected.Where(weakReference => weakReference.TryGetTarget(out var target) && target == textView).Any(); } } } diff --git a/Src/VsVimShared/Implementation/NavigateTo/NavigateToItemProviderFactory.cs b/Src/VsVimShared/Implementation/NavigateTo/NavigateToItemProviderFactory.cs index 15dfd01..20c8099 100644 --- a/Src/VsVimShared/Implementation/NavigateTo/NavigateToItemProviderFactory.cs +++ b/Src/VsVimShared/Implementation/NavigateTo/NavigateToItemProviderFactory.cs @@ -1,159 +1,159 @@ using System; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Windows.Forms; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Microsoft.VisualStudio.Text.Editor; using Vim; using System.Windows.Input; using System.Collections.Generic; using Vim.VisualStudio.Implementation.Misc; namespace Vim.VisualStudio.Implementation.NavigateTo { /// <summary> /// Certain implementations of the NagivateTo / QuickSearch feature will select the /// target of the navigation. This causes VsVim to incorrectly enter Visual Mode and /// is distracting to developers. This set of types is intended to prevent the entering /// of visual mode in this scenario /// </summary> [Export(typeof(INavigateToItemProviderFactory))] [Export(typeof(IVisualModeSelectionOverride))] internal sealed class NavigateToItemProviderFactory : INavigateToItemProviderFactory, IThreadCommunicator, IVisualModeSelectionOverride { /// <summary> /// Ideally we would use IProtectedOperations here. However NavigateTo Window is a Windows Form /// window and it suppresses the pumping of the WPF message loop which IProtectedOperations /// depends on. Using the WindowsFormsSynchronizationContext out of necessity here /// </summary> private readonly SynchronizationContext _synchronizationContext; private readonly IVim _vim; private readonly ITextManager _textManager; private readonly UnwantedSelectionHandler _unwantedSelectionHandler; private bool _inSearch; [ImportingConstructor] internal NavigateToItemProviderFactory(IVim vim, ITextManager textManager) { _vim = vim; _textManager = textManager; _synchronizationContext = WindowsFormsSynchronizationContext.Current; - _unwantedSelectionHandler = new UnwantedSelectionHandler(_vim, _textManager); + _unwantedSelectionHandler = new UnwantedSelectionHandler(_vim); } private void OnSearchStarted(string searchText) { _unwantedSelectionHandler.PreAction(); _inSearch = true; VimTrace.TraceInfo("NavigateTo Start: {0}", searchText); } private void OnSearchStopped(string searchText) { VimTrace.TraceInfo("NavigateTo Stop: {0}", searchText); if (_inSearch) { _inSearch = false; _unwantedSelectionHandler.PostAction(); } } private void Dispose() { VimTrace.TraceInfo("NavigateTo Disposed"); // In some configurations the C++ editor will not set focus to the ITextView which is displayed // as a result of completing a NavigateTo operation. Instead focus will be on the navigation // bar. This is not a function of VsVim but does mess up the general keyboard usage and // hence we force the focus to be correct // // Note: The exact scenarios under which this happens is not well understood. It does repro under // a clean machine and Windows 8.1 but doesn't always repro under other configurations. Either way // need to fix if (_textManager.ActiveTextViewOptional is IWpfTextView wpfTextView && !wpfTextView.HasAggregateFocus && wpfTextView.TextSnapshot.ContentType.IsCPlusPlus()) { VimTrace.TraceInfo("NavigateTo adjust C++ focus"); Keyboard.Focus(wpfTextView.VisualElement); } } private void CallOnMainThread(Action action) { void wrappedAction() { try { action(); } catch { // Don't let the exception propagate to the message loop and take down VS } } try { _synchronizationContext.Post(_ => wrappedAction(), null); } catch { // The set of _inSearch is guaranteed to be atomic because it's a bool. In the // case an exception occurs and we can't communicate with the UI thread we should // just act as if no search is going on. Worst case Visual mode is incorrectly // entered in a few projects _inSearch = false; } } #region INavigateToItemProviderFactory /// <summary> /// WARNING!!! This method is executed from a background thread /// </summary> bool INavigateToItemProviderFactory.TryCreateNavigateToItemProvider(IServiceProvider serviceProvider, out INavigateToItemProvider navigateToItemProvider) { navigateToItemProvider = new NavigateToItemProvider(this); return true; } #endregion #region IThreadCommunicator /// <summary> /// WARNING!!! This method is executed from a background thread /// </summary> void IThreadCommunicator.StartSearch(string searchText) { CallOnMainThread(() => OnSearchStarted(searchText)); } /// <summary> /// WARNING!!! This method is executed from a background thread /// </summary> void IThreadCommunicator.StopSearch(string searchText) { CallOnMainThread(() => OnSearchStopped(searchText)); } /// <summary> /// WARNING!!! This method is executed from a background thread /// </summary> void IThreadCommunicator.Dispose() { CallOnMainThread(Dispose); } #endregion #region IVisualModeSelectionOverride bool IVisualModeSelectionOverride.IsInsertModePreferred(ITextView textView) { return _inSearch; } #endregion } }
VsVim/VsVim
a11afcd2d1c5b6681710f01594c046b045b2c11f
Use backing line number editor option for VS2017
diff --git a/Src/VimCore/LineNumbersMarginOption.fs b/Src/VimCore/LineNumbersMarginOption.fs new file mode 100644 index 0000000..24d8789 --- /dev/null +++ b/Src/VimCore/LineNumbersMarginOption.fs @@ -0,0 +1,21 @@ +#light + +namespace Vim +open Microsoft.VisualStudio.Text.Editor +open System.ComponentModel.Composition + +module LineNumbersMarginOptions = + + [<Literal>] + let LineNumbersMarginOptionName = "VsVimLineNumbersMarginOption" + + let LineNumbersMarginOptionId = new EditorOptionKey<bool>(LineNumbersMarginOptionName) + +[<Export(typeof<EditorOptionDefinition>)>] +[<Sealed>] +type public VsVimLineNumbersMarginOption() = + inherit EditorOptionDefinition<bool>() + override x.Default + with get() = false + override x.Key + with get() = LineNumbersMarginOptions.LineNumbersMarginOptionId diff --git a/Src/VimCore/VimCore.fsproj b/Src/VimCore/VimCore.fsproj index 473f63f..8bd6da1 100644 --- a/Src/VimCore/VimCore.fsproj +++ b/Src/VimCore/VimCore.fsproj @@ -1,169 +1,170 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Vim.Core</RootNamespace> <AssemblyName>Vim.Core</AssemblyName> <TargetFramework>net45</TargetFramework> <OtherFlags>--standalone</OtherFlags> <NoWarn>2011</NoWarn> <DisableImplicitFSharpCoreReference>true</DisableImplicitFSharpCoreReference> <DebugType>portable</DebugType> </PropertyGroup> <ItemGroup> <None Include="README.md" /> <Compile Include="Resources.fs" /> <Compile Include="Constants.fs" /> <Compile Include="FSharpUtil.fs" /> <Compile Include="VimTrace.fs" /> <Compile Include="StringUtil.fs" /> <Compile Include="Util.fs" /> <Compile Include="VimKey.fs" /> <Compile Include="KeyInput.fsi" /> <Compile Include="KeyInput.fs" /> <Compile Include="Unicode.fsi" /> <Compile Include="Unicode.fs" /> <Compile Include="CoreTypes.fs" /> <Compile Include="EditorUtil.fs" /> <Compile Include="Register.fs" /> <Compile Include="VimCharSet.fsi" /> <Compile Include="VimCharSet.fs" /> <Compile Include="VimSettingsInterface.fs" /> <Compile Include="Interpreter_Expression.fs" /> <Compile Include="TaggingInterfaces.fs" /> <Compile Include="WordUtil.fsi" /> <Compile Include="WordUtil.fs" /> <Compile Include="CoreInterfaces.fs" /> <Compile Include="CoreInternalInterfaces.fs" /> <Compile Include="CountCapture.fs" /> <Compile Include="VimRegexOptions.fs" /> <Compile Include="VimRegex.fsi" /> <Compile Include="VimRegex.fs" /> <Compile Include="MefInterfaces.fs" /> <Compile Include="KeyNotationUtil.fsi" /> <Compile Include="KeyNotationUtil.fs" /> <Compile Include="DigraphUtil.fs" /> <Compile Include="MotionCapture.fs" /> <Compile Include="RegexUtil.fs" /> <Compile Include="HistoryUtil.fsi" /> <Compile Include="HistoryUtil.fs" /> <Compile Include="PatternUtil.fs" /> <Compile Include="CommonOperations.fsi" /> <Compile Include="CommonOperations.fs" /> <Compile Include="Interpreter_Tokens.fs" /> <Compile Include="Interpreter_Tokenizer.fsi" /> <Compile Include="Interpreter_Tokenizer.fs" /> <Compile Include="Interpreter_Parser.fsi" /> <Compile Include="Interpreter_Parser.fs" /> <Compile Include="Interpreter_Interpreter.fsi" /> <Compile Include="Interpreter_Interpreter.fs" /> <Compile Include="CommandFactory.fsi" /> <Compile Include="CommandFactory.fs" /> <Compile Include="Modes_Command_CommandMode.fsi" /> <Compile Include="Modes_Command_CommandMode.fs" /> <Compile Include="Modes_Normal_NormalMode.fsi" /> <Compile Include="Modes_Normal_NormalMode.fs" /> <Compile Include="Modes_Insert_Components.fs" /> <Compile Include="Modes_Insert_InsertMode.fsi" /> <Compile Include="Modes_Insert_InsertMode.fs" /> <Compile Include="Modes_Visual_ISelectionTracker.fs" /> <Compile Include="Modes_Visual_SelectionTracker.fs" /> <Compile Include="Modes_Visual_VisualMode.fsi" /> <Compile Include="Modes_Visual_VisualMode.fs" /> <Compile Include="Modes_Visual_SelectMode.fsi" /> <Compile Include="Modes_Visual_SelectMode.fs" /> <Compile Include="Modes_SubstituteConfirm_SubstituteConfirmMode.fsi" /> <Compile Include="Modes_SubstituteConfirm_SubstituteConfirmMode.fs" /> <Compile Include="IncrementalSearch.fsi" /> <Compile Include="IncrementalSearch.fs" /> <Compile Include="CommandUtil.fsi" /> <Compile Include="CommandUtil.fs" /> <Compile Include="InsertUtil.fsi" /> <Compile Include="InsertUtil.fs" /> <Compile Include="TaggerUtil.fsi" /> <Compile Include="TaggerUtil.fs" /> <Compile Include="Tagger.fsi" /> <Compile Include="Tagger.fs" /> <Compile Include="CaretChangeTracker.fsi" /> <Compile Include="CaretChangeTracker.fs" /> <Compile Include="SelectionChangeTracker.fsi" /> <Compile Include="SelectionChangeTracker.fs" /> <Compile Include="MultiSelectionTracker.fsi" /> <Compile Include="MultiSelectionTracker.fs" /> <Compile Include="FoldManager.fsi" /> <Compile Include="FoldManager.fs" /> <Compile Include="ModeLineInterpreter.fsi" /> <Compile Include="ModeLineInterpreter.fs" /> <Compile Include="VimTextBuffer.fsi" /> <Compile Include="VimTextBuffer.fs" /> <Compile Include="VimBuffer.fsi" /> <Compile Include="VimBuffer.fs" /> <Compile Include="TextObjectUtil.fsi" /> <Compile Include="TextObjectUtil.fs" /> <Compile Include="MotionUtil.fsi" /> <Compile Include="MotionUtil.fs" /> <Compile Include="SearchService.fsi" /> <Compile Include="SearchService.fs" /> <Compile Include="RegisterMap.fsi" /> <Compile Include="RegisterMap.fs" /> <Compile Include="CaretRegisterMap.fsi" /> <Compile Include="CaretRegisterMap.fs" /> <Compile Include="ExternalEdit.fs" /> <Compile Include="DisabledMode.fs" /> <Compile Include="MarkMap.fsi" /> <Compile Include="MarkMap.fs" /> <Compile Include="MacroRecorder.fsi" /> <Compile Include="MacroRecorder.fs" /> <Compile Include="KeyMap.fsi" /> <Compile Include="KeyMap.fs" /> <Compile Include="DigraphMap.fsi" /> <Compile Include="DigraphMap.fs" /> <Compile Include="JumpList.fs" /> + <Compile Include="LineNumbersMarginOption.fs" /> <Compile Include="VimSettings.fsi" /> <Compile Include="VimSettings.fs" /> <Compile Include="FileSystem.fs" /> <Compile Include="UndoRedoOperations.fsi" /> <Compile Include="UndoRedoOperations.fs" /> <Compile Include="CommandRunner.fsi" /> <Compile Include="CommandRunner.fs" /> <Compile Include="AutoCommandRunner.fsi" /> <Compile Include="AutoCommandRunner.fs" /> <Compile Include="Vim.fs" /> <Compile Include="StatusUtil.fsi" /> <Compile Include="StatusUtil.fs" /> <Compile Include="LineChangeTracker.fsi" /> <Compile Include="LineChangeTracker.fs" /> <Compile Include="MefComponents.fsi" /> <Compile Include="MefComponents.fs" /> <Compile Include="FSharpExtensions.fs" /> <Compile Include="AssemblyInfo.fs" /> </ItemGroup> <ItemGroup> <!-- Using element form vs. attributes to work around NuGet restore bug https://github.com/NuGet/Home/issues/6367 https://github.com/dotnet/project-system/issues/3493 --> <PackageReference Include="FSharp.Core"> <Version>4.2.3</Version> <PrivateAssets>all</PrivateAssets> </PackageReference> <!-- Excluding thes package to avoid the auto-include that is happening via F# targets and hittnig a restore issue in 15.7 https://github.com/NuGet/Home/issues/6936 --> <PackageReference Include="System.ValueTuple"> <Version>4.3.1</Version> <ExcludeAssets>all</ExcludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <Reference Include="Microsoft.VisualStudio.CoreUtility, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="Microsoft.VisualStudio.Text.Data, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="Microsoft.VisualStudio.Text.Logic, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="Microsoft.VisualStudio.Text.UI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="mscorlib" /> <Reference Include="System" /> <Reference Include="System.ComponentModel.Composition" /> <Reference Include="System.Core" /> <Reference Include="System.Numerics" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Xml" /> </ItemGroup> </Project> diff --git a/Src/VimCore/VimSettings.fs b/Src/VimCore/VimSettings.fs index 336bbeb..6b6e78c 100644 --- a/Src/VimCore/VimSettings.fs +++ b/Src/VimCore/VimSettings.fs @@ -314,661 +314,665 @@ type internal GlobalSettings() = | c -> builder.AppendChar c i <- i + 1 if builder.Length > 0 then addOne (builder.ToString()) List.ofSeq list member x.SelectionKind = match _map.GetStringValue SelectionName with | "inclusive" -> SelectionKind.Inclusive | "old" -> SelectionKind.Exclusive | _ -> SelectionKind.Exclusive interface IVimGlobalSettings with // IVimSettings member x.Settings = _map.Settings member x.TrySetValue settingName value = _map.TrySetValue settingName value member x.TrySetValueFromString settingName strValue = _map.TrySetValueFromString settingName strValue member x.GetSetting settingName = _map.GetSetting settingName // IVimGlobalSettings member x.VimRcLocalSettings with get() = _vimRcLocalSettings and set value = _vimRcLocalSettings <- value member x.VimRcWindowSettings with get() = _vimRcWindowSettings and set value = _vimRcWindowSettings <- value member x.AddCustomSetting name abbrevation customSettingSource = x.AddCustomSetting name abbrevation customSettingSource member x.AtomicInsert with get() = _map.GetBoolValue AtomicInsertName and set value = _map.TrySetValue AtomicInsertName (SettingValue.Toggle value) |> ignore member x.Backspace with get() = _map.GetStringValue BackspaceName and set value = _map.TrySetValueFromString BackspaceName value |> ignore member x.CaretOpacity with get() = _map.GetNumberValue CaretOpacityName and set value = _map.TrySetValue CaretOpacityName (SettingValue.Number value) |> ignore member x.Clipboard with get() = _map.GetStringValue ClipboardName and set value = _map.TrySetValue ClipboardName (SettingValue.String value) |> ignore member x.ClipboardOptions with get() = x.GetCommaOptions ClipboardName ClipboardOptionsMapping ClipboardOptions.None (fun x y -> x ||| y) and set value = x.SetCommaOptions ClipboardName ClipboardOptionsMapping value Util.IsFlagSet member x.CurrentDirectoryPath with get() = _map.GetStringValue CurrentDirectoryPathName and set value = _map.TrySetValue CurrentDirectoryPathName (SettingValue.String value) |> ignore member x.CurrentDirectoryPathList = x.GetPathOptionList (_map.GetStringValue CurrentDirectoryPathName) member x.Digraph with get() = _map.GetBoolValue DigraphName and set value = _map.TrySetValue DigraphName (SettingValue.Toggle value) |> ignore member x.GlobalDefault with get() = _map.GetBoolValue GlobalDefaultName and set value = _map.TrySetValue GlobalDefaultName (SettingValue.Toggle value) |> ignore member x.HighlightSearch with get() = _map.GetBoolValue HighlightSearchName and set value = _map.TrySetValue HighlightSearchName (SettingValue.Toggle value) |> ignore member x.History with get () = _map.GetNumberValue HistoryName and set value = _map.TrySetValue HistoryName (SettingValue.Number value) |> ignore member x.IgnoreCase with get() = _map.GetBoolValue IgnoreCaseName and set value = _map.TrySetValue IgnoreCaseName (SettingValue.Toggle value) |> ignore member x.ImeCommand with get() = _map.GetBoolValue ImeCommandName and set value = _map.TrySetValue ImeCommandName (SettingValue.Toggle value) |> ignore member x.ImeDisable with get() = _map.GetBoolValue ImeDisableName and set value = _map.TrySetValue ImeDisableName (SettingValue.Toggle value) |> ignore member x.ImeInsert with get() = _map.GetNumberValue ImeInsertName and set value = _map.TrySetValue ImeInsertName (SettingValue.Number value) |> ignore member x.ImeSearch with get() = _map.GetNumberValue ImeSearchName and set value = _map.TrySetValue ImeSearchName (SettingValue.Number value) |> ignore member x.IncrementalSearch with get() = _map.GetBoolValue IncrementalSearchName and set value = _map.TrySetValue IncrementalSearchName (SettingValue.Toggle value) |> ignore member x.IsSelectionInclusive = x.SelectionKind = SelectionKind.Inclusive member x.IsSelectionPastLine = match _map.GetStringValue SelectionName with | "exclusive" -> true | "inclusive" -> true | _ -> false member x.IsIdent with get() = _map.GetStringValue IsIdentName and set value = _map.TrySetValue IsIdentName (SettingValue.String value) |> ignore member x.IsIdentCharSet with get() = match VimCharSet.TryParse (_map.GetStringValue IsIdentName) with Some s -> s | None -> SettingsDefaults.IsIdentCharSet and set value = _map.TrySetValue IsIdentName (SettingValue.String value.Text) |> ignore member x.JoinSpaces with get() = _map.GetBoolValue JoinSpacesName and set value = _map.TrySetValue JoinSpacesName (SettingValue.Toggle value) |> ignore member x.KeyModel with get() = _map.GetStringValue KeyModelName and set value = _map.TrySetValue KeyModelName (SettingValue.String value) |> ignore member x.KeyModelOptions with get() = x.GetCommaOptions KeyModelName KeyModelOptionsMapping KeyModelOptions.None (fun x y -> x ||| y) and set value = x.SetCommaOptions KeyModelName KeyModelOptionsMapping value Util.IsFlagSet member x.LastStatus with get() = _map.GetNumberValue LastStatusName and set value = _map.TrySetValue LastStatusName (SettingValue.Number value) |> ignore member x.Magic with get() = _map.GetBoolValue MagicName and set value = _map.TrySetValue MagicName (SettingValue.Toggle value) |> ignore member x.MaxMapDepth with get() = _map.GetNumberValue MaxMapDepth and set value = _map.TrySetValue MaxMapDepth (SettingValue.Number value) |> ignore member x.ModeLine with get() = _map.GetBoolValue ModeLineName and set value = _map.TrySetValue ModeLineName (SettingValue.Toggle value) |> ignore member x.ModeLines with get() = _map.GetNumberValue ModeLinesName and set value = _map.TrySetValue ModeLinesName (SettingValue.Number value) |> ignore member x.MouseModel with get() = _map.GetStringValue MouseModelName and set value = _map.TrySetValue MouseModelName (SettingValue.String value) |> ignore member x.Paragraphs with get() = _map.GetStringValue ParagraphsName and set value = _map.TrySetValue ParagraphsName (SettingValue.String value) |> ignore member x.Path with get() = _map.GetStringValue PathName and set value = _map.TrySetValue PathName (SettingValue.String value) |> ignore member x.PathList = x.GetPathOptionList (_map.GetStringValue PathName) member x.ScrollOffset with get() = _map.GetNumberValue ScrollOffsetName and set value = _map.TrySetValue ScrollOffsetName (SettingValue.Number value) |> ignore member x.Sections with get() = _map.GetStringValue SectionsName and set value = _map.TrySetValue SectionsName (SettingValue.String value) |> ignore member x.Selection with get() = _map.GetStringValue SelectionName and set value = _map.TrySetValue SelectionName (SettingValue.String value) |> ignore member x.SelectionKind = x.SelectionKind member x.SelectMode with get() = _map.GetStringValue SelectModeName and set value = _map.TrySetValue SelectModeName (SettingValue.String value) |> ignore member x.SelectModeOptions with get() = x.GetCommaOptions SelectModeName SelectModeOptionsMapping SelectModeOptions.None (fun x y -> x ||| y) and set value = x.SetCommaOptions SelectModeName SelectModeOptionsMapping value Util.IsFlagSet member x.Shell with get() = _map.GetStringValue ShellName and set value = _map.TrySetValue ShellName (SettingValue.String value) |> ignore member x.ShellFlag with get() = _map.GetStringValue ShellFlagName and set value = _map.TrySetValue ShellFlagName (SettingValue.String value) |> ignore member x.ShowCommand with get() = _map.GetBoolValue ShowCommandName and set value = _map.TrySetValue ShowCommandName (SettingValue.Toggle value) |> ignore member x.SmartCase with get() = _map.GetBoolValue SmartCaseName and set value = _map.TrySetValue SmartCaseName (SettingValue.Toggle value) |> ignore member x.StartOfLine with get() = _map.GetBoolValue StartOfLineName and set value = _map.TrySetValue StartOfLineName (SettingValue.Toggle value) |> ignore member x.StatusLine with get() = _map.GetStringValue StatusLineName and set value = _map.TrySetValue StatusLineName (SettingValue.String value) |> ignore member x.TildeOp with get() = _map.GetBoolValue TildeOpName and set value = _map.TrySetValue TildeOpName (SettingValue.Toggle value) |> ignore member x.Timeout with get() = _map.GetBoolValue TimeoutName and set value = _map.TrySetValue TimeoutName (SettingValue.Toggle value) |> ignore member x.TimeoutEx with get() = _map.GetBoolValue TimeoutExName and set value = _map.TrySetValue TimeoutExName (SettingValue.Toggle value) |> ignore member x.TimeoutLength with get() = _map.GetNumberValue TimeoutLengthName and set value = _map.TrySetValue TimeoutLengthName (SettingValue.Number value) |> ignore member x.TimeoutLengthEx with get() = _map.GetNumberValue TimeoutLengthExName and set value = _map.TrySetValue TimeoutLengthExName (SettingValue.Number value) |> ignore member x.VimRc with get() = _map.GetStringValue VimRcName and set value = _map.TrySetValue VimRcName (SettingValue.String value) |> ignore member x.VimRcPaths with get() = _map.GetStringValue VimRcPathsName and set value = _map.TrySetValue VimRcPathsName (SettingValue.String value) |> ignore member x.VirtualEdit with get() = _map.GetStringValue VirtualEditName and set value = _map.TrySetValue VirtualEditName (SettingValue.String value) |> ignore member x.VisualBell with get() = _map.GetBoolValue VisualBellName and set value = _map.TrySetValue VisualBellName (SettingValue.Toggle value) |> ignore member x.WhichWrap with get() = _map.GetStringValue WhichWrapName and set value = _map.TrySetValue WhichWrapName (SettingValue.String value) |> ignore member x.WrapScan with get() = _map.GetBoolValue WrapScanName and set value = _map.TrySetValue WrapScanName (SettingValue.Toggle value) |> ignore member x.DisableAllCommand = GlobalSettings.DisableAllCommand member x.IsBackspaceEol = x.IsCommaSubOptionPresent BackspaceName "eol" member x.IsBackspaceIndent = x.IsCommaSubOptionPresent BackspaceName "indent" member x.IsBackspaceStart = x.IsCommaSubOptionPresent BackspaceName "start" member x.IsVirtualEditBlock = x.IsCommaSubOptionPresent VirtualEditName "block" || x.IsCommaSubOptionPresent VirtualEditName "all" member x.IsVirtualEditInsert = x.IsCommaSubOptionPresent VirtualEditName "insert" || x.IsCommaSubOptionPresent VirtualEditName "all" member x.IsVirtualEditAll = x.IsCommaSubOptionPresent VirtualEditName "all" member x.IsVirtualEditOneMore = x.IsCommaSubOptionPresent VirtualEditName "onemore" || x.IsCommaSubOptionPresent VirtualEditName "all" member x.IsWhichWrapSpaceLeft = x.IsCommaSubOptionPresent WhichWrapName "b" member x.IsWhichWrapSpaceRight = x.IsCommaSubOptionPresent WhichWrapName "s" member x.IsWhichWrapCharLeft = x.IsCommaSubOptionPresent WhichWrapName "h" member x.IsWhichWrapCharRight = x.IsCommaSubOptionPresent WhichWrapName "l" member x.IsWhichWrapArrowLeft = x.IsCommaSubOptionPresent WhichWrapName "<" member x.IsWhichWrapArrowRight = x.IsCommaSubOptionPresent WhichWrapName ">" member x.IsWhichWrapTilde = x.IsCommaSubOptionPresent WhichWrapName "~" member x.IsWhichWrapArrowLeftInsert = x.IsCommaSubOptionPresent WhichWrapName "[" member x.IsWhichWrapArrowRightInsert = x.IsCommaSubOptionPresent WhichWrapName "]" [<CLIEvent>] member x.SettingChanged = _map.SettingChanged type internal LocalSettings ( _globalSettings: IVimGlobalSettings ) = static let LocalSettingInfoList = [| (AutoIndentName, "ai", SettingValue.Toggle false, SettingOptions.None) (CommentsName, "com", SettingValue.String SettingsDefaults.Comments, SettingOptions.None) (EndOfLineName, "eol", SettingValue.Toggle true, SettingOptions.None) (ExpandTabName, "et", SettingValue.Toggle false, SettingOptions.None) (FixEndOfLineName, "fixeol", SettingValue.Toggle false, SettingOptions.None) (IsKeywordName, "isk", SettingValue.String SettingsDefaults.IsKeywordCharSet.Text, SettingOptions.None) (ListName, "list", SettingValue.Toggle false, SettingOptions.None) (NumberFormatsName, "nf", SettingValue.String "bin,octal,hex", SettingOptions.None) (NumberName, "nu", SettingValue.Toggle false, SettingOptions.None) (QuoteEscapeName, "qe", SettingValue.String @"\", SettingOptions.None) (RelativeNumberName, "rnu", SettingValue.Toggle false, SettingOptions.None) (ShiftWidthName, "sw", SettingValue.Number 8, SettingOptions.None) (SoftTabStopName, "sts", SettingValue.Number 0, SettingOptions.None) (TabStopName, "ts", SettingValue.Number 8, SettingOptions.None) (TextWidthName, "tw", SettingValue.Number 0, SettingOptions.None) |] static let LocalSettingList = LocalSettingInfoList |> Seq.map (fun (name, abbrev, defaultValue, options) -> { Name = name; Abbreviation = abbrev; LiveSettingValue = LiveSettingValue.Create defaultValue; IsGlobal = false; SettingOptions = options }) let _map = SettingsMap(LocalSettingList) member x.Defaults = match _globalSettings.VimRcLocalSettings with | Some localSettings -> localSettings | None -> LocalSettings(_globalSettings) :> IVimLocalSettings member x.Map = _map static member Copy (settings: IVimLocalSettings) = let copy = LocalSettings(settings.GlobalSettings) settings.Settings |> Seq.filter (fun s -> not s.IsValueCalculated) |> Seq.iter (fun s -> copy.Map.TrySetValue s.Name s.Value |> ignore) copy :> IVimLocalSettings member x.IsNumberFormatSupported numberFormat = // The format is supported if the name is in the comma delimited value let isSupported format = _map.GetStringValue NumberFormatsName |> StringUtil.Split ',' |> Seq.exists (fun value -> value = format) match numberFormat with | NumberFormat.Decimal -> // This is always supported independent of the option value true | NumberFormat.Binary -> isSupported "bin" | NumberFormat.Octal -> isSupported "octal" | NumberFormat.Hex -> isSupported "hex" | NumberFormat.Alpha -> isSupported "alpha" member x.TrySetValue settingName value = if _map.OwnsSetting settingName then _map.TrySetValue settingName value else _globalSettings.TrySetValue settingName value member x.TrySetValueFromString settingName strValue = if _map.OwnsSetting settingName then _map.TrySetValueFromString settingName strValue else _globalSettings.TrySetValueFromString settingName strValue member x.GetSetting settingName = if _map.OwnsSetting settingName then _map.GetSetting settingName else _globalSettings.GetSetting settingName interface IVimLocalSettings with // IVimSettings member x.Defaults = x.Defaults member x.Settings = _map.Settings member x.TrySetValue settingName value = x.TrySetValue settingName value member x.TrySetValueFromString settingName strValue = x.TrySetValueFromString settingName strValue member x.GetSetting settingName = x.GetSetting settingName member x.GlobalSettings = _globalSettings member x.AutoIndent with get() = _map.GetBoolValue AutoIndentName and set value = _map.TrySetValue AutoIndentName (SettingValue.Toggle value) |> ignore member x.Comments with get() = _map.GetStringValue CommentsName and set value = _map.TrySetValue CommentsName (SettingValue.String value) |> ignore member x.EndOfLine with get() = _map.GetBoolValue EndOfLineName and set value = _map.TrySetValue EndOfLineName (SettingValue.Toggle value) |> ignore member x.ExpandTab with get() = _map.GetBoolValue ExpandTabName and set value = _map.TrySetValue ExpandTabName (SettingValue.Toggle value) |> ignore member x.FixEndOfLine with get() = _map.GetBoolValue FixEndOfLineName and set value = _map.TrySetValue FixEndOfLineName (SettingValue.Toggle value) |> ignore member x.IsKeyword with get() = _map.GetStringValue IsKeywordName and set value = _map.TrySetValue IsKeywordName (SettingValue.String value) |> ignore member x.IsKeywordCharSet with get() = match VimCharSet.TryParse (_map.GetStringValue IsKeywordName) with Some s -> s | None -> SettingsDefaults.IsKeywordCharSet and set value = _map.TrySetValue IsKeywordName (SettingValue.String value.Text) |> ignore member x.List with get() = _map.GetBoolValue ListName and set value = _map.TrySetValue ListName (SettingValue.Toggle value) |> ignore member x.Number with get() = _map.GetBoolValue NumberName and set value = _map.TrySetValue NumberName (SettingValue.Toggle value) |> ignore member x.NumberFormats with get() = _map.GetStringValue NumberFormatsName and set value = _map.TrySetValue NumberFormatsName (SettingValue.String value) |> ignore member x.QuoteEscape with get() = _map.GetStringValue QuoteEscapeName and set value = _map.TrySetValue QuoteEscapeName (SettingValue.String value) |> ignore member x.RelativeNumber with get() = _map.GetBoolValue RelativeNumberName and set value = _map.TrySetValue RelativeNumberName (SettingValue.Toggle value) |> ignore member x.SoftTabStop with get() = _map.GetNumberValue SoftTabStopName and set value = _map.TrySetValue SoftTabStopName (SettingValue.Number value) |> ignore member x.ShiftWidth with get() = _map.GetNumberValue ShiftWidthName and set value = _map.TrySetValue ShiftWidthName (SettingValue.Number value) |> ignore member x.TabStop with get() = _map.GetNumberValue TabStopName and set value = _map.TrySetValue TabStopName (SettingValue.Number value) |> ignore member x.TextWidth with get() = _map.GetNumberValue TextWidthName and set value = _map.TrySetValue TextWidthName (SettingValue.Number value) |> ignore member x.IsNumberFormatSupported numberFormat = x.IsNumberFormatSupported numberFormat [<CLIEvent>] member x.SettingChanged = _map.SettingChanged type internal WindowSettings ( _globalSettings: IVimGlobalSettings, _textView: ITextView option ) as this = static let WindowSettingInfoList = [| (CursorLineName, "cul", SettingValue.Toggle false, SettingOptions.None) (ScrollName, "scr", SettingValue.Number 25, SettingOptions.None) (WrapName, WrapName, SettingValue.Toggle false, SettingOptions.None) |] static let WindowSettingList = WindowSettingInfoList |> Seq.map (fun (name, abbrev, defaultValue, options) -> { Name = name; Abbreviation = abbrev; LiveSettingValue = LiveSettingValue.Create defaultValue; IsGlobal = false; SettingOptions = options }) let _map = SettingsMap(WindowSettingList) do let setting = _map.GetSetting ScrollName |> Option.get let liveSettingValue = LiveSettingValue.CalculatedNumber (None, this.CalculateScroll) let setting = { setting with LiveSettingValue = liveSettingValue } _map.ReplaceSetting setting new (settings) = WindowSettings(settings, None) new (settings, textView: ITextView) = WindowSettings(settings, Some textView) member x.Defaults = match _globalSettings.VimRcWindowSettings with | Some windowSettings -> windowSettings | None -> WindowSettings(_globalSettings, _textView) :> IVimWindowSettings member x.Map = _map /// Calculate the scroll value as specified in the Vim documentation. Should be half the number of /// visible lines member x.CalculateScroll() = let defaultValue = 10 match _textView with | None -> defaultValue | Some textView -> int (textView.ViewportHeight / textView.LineHeight / 2.0 + 0.5) static member Copy (settings: IVimWindowSettings) = let copy = WindowSettings(settings.GlobalSettings) settings.Settings |> Seq.filter (fun s -> not s.IsValueCalculated) |> Seq.iter (fun s -> copy.Map.TrySetValue s.Name s.Value |> ignore) copy :> IVimWindowSettings interface IVimWindowSettings with member x.Defaults = x.Defaults member x.Settings = _map.Settings member x.TrySetValue settingName value = if _map.OwnsSetting settingName then _map.TrySetValue settingName value else _globalSettings.TrySetValue settingName value member x.TrySetValueFromString settingName strValue = if _map.OwnsSetting settingName then _map.TrySetValueFromString settingName strValue else _globalSettings.TrySetValueFromString settingName strValue member x.GetSetting settingName = if _map.OwnsSetting settingName then _map.GetSetting settingName else _globalSettings.GetSetting settingName member x.GlobalSettings = _globalSettings member x.CursorLine with get() = _map.GetBoolValue CursorLineName and set value = _map.TrySetValue CursorLineName (SettingValue.Toggle value) |> ignore member x.Scroll with get() = _map.GetNumberValue ScrollName and set value = _map.TrySetValue ScrollName (SettingValue.Number value) |> ignore member x.Wrap with get() = _map.GetBoolValue WrapName and set value = _map.TrySetValue WrapName (SettingValue.Toggle value) |> ignore [<CLIEvent>] member x.SettingChanged = _map.SettingChanged /// Certain changes need to be synchronized between the editor, local and global /// settings. This MEF component takes care of that synchronization [<Export(typeof<IEditorToSettingsSynchronizer>)>] type internal EditorToSettingSynchronizer [<ImportingConstructor>] () = let _syncronizingSet = System.Collections.Generic.HashSet<IVimLocalSettings>() let _settingList = System.Collections.Generic.List<SettingSyncData>() let _key = obj() do _settingList.Add( { EditorOptionKey = DefaultOptions.TabSizeOptionId.Name GetEditorValue = SettingSyncData.GetNumberValueFunc DefaultOptions.TabSizeOptionId VimSettingNames = [LocalSettingNames.TabStopName] GetVimValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.TabStopName true SetVimValue = SettingSyncData.SetVimValueFunc LocalSettingNames.TabStopName true IsLocal = true }) _settingList.Add( { EditorOptionKey = DefaultOptions.IndentSizeOptionId.Name GetEditorValue = SettingSyncData.GetNumberValueFunc DefaultOptions.IndentSizeOptionId VimSettingNames = [LocalSettingNames.ShiftWidthName] GetVimValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ShiftWidthName true SetVimValue = SettingSyncData.SetVimValueFunc LocalSettingNames.ShiftWidthName true IsLocal = true }) _settingList.Add( { EditorOptionKey = DefaultOptions.ConvertTabsToSpacesOptionId.Name GetEditorValue = SettingSyncData.GetBoolValueFunc DefaultOptions.ConvertTabsToSpacesOptionId VimSettingNames = [LocalSettingNames.ExpandTabName] GetVimValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ExpandTabName true SetVimValue = SettingSyncData.SetVimValueFunc LocalSettingNames.ExpandTabName true IsLocal = true }) _settingList.Add( { EditorOptionKey = DefaultTextViewHostOptions.LineNumberMarginId.Name GetEditorValue = SettingSyncData.GetBoolValueFunc DefaultTextViewHostOptions.LineNumberMarginId VimSettingNames = [LocalSettingNames.NumberName; LocalSettingNames.RelativeNumberName] GetVimValue = (fun vimBuffer -> let localSettings = vimBuffer.LocalSettings (localSettings.Number || localSettings.RelativeNumber) |> box) SetVimValue = (fun vimBuffer value -> let localSettings = vimBuffer.LocalSettings let enableNumber, enableRelativeNumber = match value with | SettingValue.Toggle true -> // The editor line number option is enabled. If // either or both of the user defaults for 'number' // and 'relativenumber' are set, then use those // defaults. Otherwise enable only 'number'. let localSettingDefaults = localSettings.Defaults let defaultNumber = localSettingDefaults.Number let defaultRelativeNumber = localSettingDefaults.RelativeNumber if defaultNumber || defaultRelativeNumber then defaultNumber, defaultRelativeNumber else true, false | _ -> false, false let setSettingValue name enableSetting = SettingValue.Toggle enableSetting |> localSettings.TrySetValue name |> ignore setSettingValue LocalSettingNames.NumberName enableNumber - setSettingValue LocalSettingNames.RelativeNumberName enableRelativeNumber) + setSettingValue LocalSettingNames.RelativeNumberName enableRelativeNumber + let editorOptions = vimBuffer.TextView.Options + if editorOptions <> null then + let optionId = LineNumbersMarginOptions.LineNumbersMarginOptionId + let optionValue = enableNumber || enableRelativeNumber + EditorOptionsUtil.SetOptionValue editorOptions optionId optionValue) IsLocal = true }) _settingList.Add( { EditorOptionKey = DefaultTextViewOptions.WordWrapStyleId.Name GetEditorValue = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions DefaultTextViewOptions.WordWrapStyleId with | None -> None | Some s -> Util.IsFlagSet s WordWrapStyles.WordWrap |> SettingValue.Toggle |> Option.Some) VimSettingNames = [WindowSettingNames.WrapName] GetVimValue = (fun vimBuffer -> let windowSettings = vimBuffer.WindowSettings // Wrap is a difficult option because vim has wrap as on / off while the core editor has // 3 different kinds of wrapping. If we default to only one of them then we will constantly // be undoing user settings. Hence we consider anything but off to be on and hence won't change it let wordWrap = if windowSettings.Wrap then let vimHost = vimBuffer.Vim.VimHost vimHost.GetWordWrapStyle vimBuffer.TextView else WordWrapStyles.None box wordWrap) SetVimValue = SettingSyncData.SetVimValueFunc WindowSettingNames.WrapName false IsLocal = false }) _settingList.Add( { EditorOptionKey = DefaultTextViewOptions.UseVisibleWhitespaceId.Name GetEditorValue = SettingSyncData.GetBoolValueFunc DefaultTextViewOptions.UseVisibleWhitespaceId VimSettingNames = [LocalSettingNames.ListName] GetVimValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ListName true SetVimValue = SettingSyncData.SetVimValueFunc LocalSettingNames.ListName true IsLocal = true }) member x.StartSynchronizing (vimBuffer: IVimBuffer) settingSyncSource = let properties = vimBuffer.TextView.Properties if not (properties.ContainsProperty _key) then properties.AddProperty(_key, _key) x.SetupSynchronization vimBuffer // Vim doesn't consider folding an undo operation, and neither does VsVim (issue #2184). vimBuffer.TextView.Options.SetOptionValue(DefaultTextViewOptions.OutliningUndoOptionId, false) match settingSyncSource with | SettingSyncSource.Editor -> x.CopyEditorToVimSettings vimBuffer | SettingSyncSource.Vim -> x.CopyVimToEditorSettings vimBuffer // Any applicable modeline takes precedence over both the editor // and the default settings. Apply modeline settings now that we // have synchronized the local settings between the editor and the // defaults. match vimBuffer.VimTextBuffer.CheckModeLine vimBuffer.WindowSettings with | Some modeLine, Some badOption -> Resources.Common_InvalidModeLineSetting badOption modeLine |> vimBuffer.VimBufferData.StatusUtil.OnError | _ -> () member x.SetupSynchronization (vimBuffer: IVimBuffer) = let editorOptions = vimBuffer.TextView.Options if editorOptions <> null then let properties = vimBuffer.TextView.Properties let bag = DisposableBag() // Raised when a local setting is changed. We need to inspect this setting and // determine if it's an interesting setting and if so synchronize it with the // editor options // // Cast up to IVimSettings to avoid the F# bug of accessing a CLIEvent from // a derived interface let localSettings = vimBuffer.LocalSettings (localSettings :> IVimSettings).SettingChanged |> Observable.filter (fun args -> x.IsTrackedLocalSetting args.Setting) |> Observable.subscribe (fun _ -> x.CopyVimToEditorSettings vimBuffer) |> bag.Add // Cast up to IVimSettings to avoid the F# bug of accessing a CLIEvent from // a derived interface let windowSettings = vimBuffer.WindowSettings (windowSettings :> IVimSettings).SettingChanged |> Observable.filter (fun args -> x.IsTrackedWindowSetting args.Setting) |> Observable.subscribe (fun _ -> x.CopyVimToEditorSettings vimBuffer) |> bag.Add /// Raised when an editor option is changed. If it's one of the values we care about /// then we need to sync to the local settings editorOptions.OptionChanged |> Observable.filter (fun e -> x.IsTrackedEditorSetting e.OptionId) |> Observable.subscribe (fun _ -> x.CopyEditorToVimSettings vimBuffer) |> bag.Add // Finally we need to clean up our listeners when the buffer is closed. At // that point synchronization is no longer needed vimBuffer.Closed |> Observable.add (fun _ -> properties.RemoveProperty _key |> ignore bag.DisposeAll()) /// Is this a local setting of note member x.IsTrackedLocalSetting (setting: Setting) = _settingList |> Seq.exists (fun x -> x.IsLocal && List.contains setting.Name x.VimSettingNames) /// Is this a window setting of note member x.IsTrackedWindowSetting (setting: Setting) = _settingList |> Seq.exists (fun x -> not x.IsLocal && List.contains setting.Name x.VimSettingNames) /// Is this an editor setting of note member x.IsTrackedEditorSetting optionId = _settingList |> Seq.exists (fun x -> x.EditorOptionKey = optionId) /// Synchronize the settings if needed. Prevent recursive sync's here member x.TrySync (vimBuffer: IVimBuffer) syncFunc = let editorOptions = vimBuffer.TextView.Options if editorOptions <> null then let localSettings = vimBuffer.LocalSettings if _syncronizingSet.Add(localSettings) then try syncFunc vimBuffer editorOptions finally _syncronizingSet.Remove(localSettings) |> ignore /// Synchronize the settings from the editor to the local settings. Do not /// call this directly but instead call through SynchronizeSettings member x.CopyVimToEditorSettings vimBuffer = x.TrySync vimBuffer (fun vimBuffer editorOptions -> for data in _settingList do - let settings = data.GetSettings vimBuffer let value = data.GetVimValue vimBuffer if value <> null then editorOptions.SetOptionValue(data.EditorOptionKey, value)) /// Synchronize the settings from the local settings to the editor. Do not /// call this directly but instead call through SynchronizeSettings member x.CopyEditorToVimSettings (vimBuffer: IVimBuffer) = x.TrySync vimBuffer (fun vimBuffer editorOptions -> for data in _settingList do match data.GetEditorValue editorOptions with | None -> () | Some value -> data.SetVimValue vimBuffer value) interface IEditorToSettingsSynchronizer with member x.StartSynchronizing vimBuffer settingSyncSource = x.StartSynchronizing vimBuffer settingSyncSource member x.SyncSetting data = _settingList.Add data diff --git a/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMarginFactory.cs b/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMarginFactory.cs index 2470c93..d7708ed 100644 --- a/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMarginFactory.cs +++ b/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMarginFactory.cs @@ -1,68 +1,68 @@ using System; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Vim.UI.Wpf.Implementation.RelativeLineNumbers { [Export(typeof(IWpfTextViewMarginProvider))] [Name(VimWpfConstants.LineNumbersMarginName)] [MarginContainer(PredefinedMarginNames.LeftSelection)] [Order(Before = PredefinedMarginNames.Spacer, After = PredefinedMarginNames.LineNumber)] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Document)] [TextViewRole(PredefinedTextViewRoles.EmbeddedPeekTextView)] - [DeferCreation(OptionName = DefaultTextViewHostOptions.LineNumberMarginName)] + [DeferCreation(OptionName = LineNumbersMarginOptions.LineNumbersMarginOptionName)] internal sealed class RelativeLineNumbersMarginFactory : IWpfTextViewMarginProvider { private readonly IClassificationFormatMapService _formatMapService; private readonly IClassificationTypeRegistryService _typeRegistryService; private readonly IProtectedOperations _protectedOperations; private readonly IVim _vim; [ImportingConstructor] internal RelativeLineNumbersMarginFactory( IClassificationFormatMapService formatMapService, IClassificationTypeRegistryService typeRegistryService, IProtectedOperations protectedOperations, IVim vim) { _formatMapService = formatMapService ?? throw new ArgumentNullException(nameof(formatMapService)); _typeRegistryService = typeRegistryService ?? throw new ArgumentNullException(nameof(typeRegistryService)); _protectedOperations = protectedOperations ?? throw new ArgumentNullException(nameof(protectedOperations)); _vim = vim ?? throw new ArgumentNullException(nameof(vim)); } public IWpfTextViewMargin CreateMargin( IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin marginContainer) { var textView = wpfTextViewHost?.TextView ?? throw new ArgumentNullException(nameof(wpfTextViewHost)); var vimBuffer = _vim.GetOrCreateVimBuffer(textView); var formatMap = _formatMapService.GetClassificationFormatMap(textView); var formatProvider = new LineNumberFormatTracker( textView, formatMap, _typeRegistryService); return new RelativeLineNumbersMargin( textView, formatProvider, vimBuffer.LocalSettings, marginContainer, _protectedOperations); } } }
VsVim/VsVim
9320812b167c2758c3a94f5b2ff04f677450796f
Unify add and split selection into start
diff --git a/Documentation/Multiple Selections.md b/Documentation/Multiple Selections.md index a66cdd1..7071c55 100644 --- a/Documentation/Multiple Selections.md +++ b/Documentation/Multiple Selections.md @@ -1,97 +1,97 @@ ### Multiple Carets / Multiple Cursors / Multiple Selections If the host supports multiple selections, VsVim will also support them. #### Architecture Most parts of VsVim are unware of multiple selections. In order to keep things simple and preserve the single selection model for most of VsVim, there are two major components that handle multiple selections: - Running mode commands for all selections (`ICommonOperations.RunForAllSelections`) - The multi-selection tracker (`MultiSelectionTracker`) For commands where it makes sense to run them for each caret or selection, the corresponding command runner will wrap the running of a single command into a batch execution for each selection using `RunForAllSelections`. Then, while running an individual command, the multi-selection infrastructure will: - Set a single temporary selection, including a caret position - Run the command as if there were a single selection - Determine the desired resulting selection from the command result When all the individual commands have run, the accumulated selections will be set all at once. This causes the non-multi-selection aware code to still see the primary selection as the real and only selection, while maintaining the secondary selections behind the scenes. #### The Multi-Selection API Unfortunately, not all versions of the editor API support multiple selections. In order to handle this, there are two API entry points in the Vim host: - `IVimHost.GetSelectedSpans` - member - `IVimHost.SetSelectedSpans` - member A selected span is a triple of caret point, anchor point, and active point. All three values are virtual snapshot points. For multiple caret support, a caret is just a zero-width selection. Selected spans are associated with a specific text view, just like the normal caret and normal selection. If there is no multi-selection support, getting the selected spans always returns a single (possibly empty) span and setting multiple selected spans ignores all of the secondary selections. If there is multi-selection support, then the first selected span is the primary selection and any subsequent selected spans are secondary selections, sorted in ascending order by position within the text buffer. In order to insulate the code base from the host, all consumers who use the multi-selection API access the selections using related APIs in the common operations module: - `ICommonOperations.SelectedSpans` - property - `ICommonOperations.SetSelectedSpans` - member - `ICommonOperations.SelectedSpansSet` - event #### VsVim Key Bindings - Key inputs - description (applicable modes) - `<C-A-LeftMouse>` - add or remove caret (normal, visual, select, insert) - `<C-A-2-LeftMouse>` - add a new selected word or token (normal, visual, select, insert) - `<C-A-Up>` and `<C-A-Down>` - add a new caret on an adjecent line (normal, insert) - `<C-A-Up>` and `<C-A-Down>` - add a new selection on an adjecent line (visual, select) -- `<C-A-I>` - split selection into carets (visual, select) - `<C-A-N>` - select word or token at caret (normal) -- `<C-A-N>` - add next occurrence of primary selection (visual, select) +- `<C-A-N>` (single-line selection) - add next occurrence of primary selection (visual, select) +- `<C-A-N>` (multi-line selection) - split selection into carets (visual, select) - `<C-A-P>` - restore previous multi-carets or multi-selections (normal) - `<Esc>` - clear secondary carets (normal) - `<C-c>` - clear secondary carets or selections (normal, visual, insert) #### The Unnamaed Register Each caret gets their own unnamed register. All secondary caret's unnamed registers are copied from the "real" unnamed register whenever a caret is added or removed. The result is that if you put from the unnamed register at all carets immediately after creating them, all carets will put the same value. But if you yank text and the put it while there are multiple carets, each caret will put what that caret yanked. #### Interoperation with Visual Studio Visual Studio itself provides some commands for multiple carets. VsVim supports multi-selection operations performed by external components such as the Visual Studio editor, a language service, a code assistant like Resharper, or event another Visual Studio extension. #### Visual Studio Key Bindings - `<S-A-.>` - add selection for the next occurrence of the current word - `<S-A-;>` - add selections for all occurrences of the current word #### Testing The multi-selection feature is accessed through the Vim host interface. During testing the `MockVimHost` conditionally supports the the full multi-selection APIs (controlled by the `IsMultSelectionSupported` property), which are emulated by `MockMultiSelection`. diff --git a/Src/VimCore/CommandUtil.fs b/Src/VimCore/CommandUtil.fs index 59fcb9d..19e32e3 100644 --- a/Src/VimCore/CommandUtil.fs +++ b/Src/VimCore/CommandUtil.fs @@ -2668,1844 +2668,1852 @@ type internal CommandUtil let repeatData = match commandResult with | CommandResult.Completed (ModeSwitch.SwitchModeWithArgument (ModeKind.Insert, ModeArgument.InsertWithCount count)) -> Some { CommandData.Default with Count = Some count } | _ -> None // Run the next command in sequence. Only continue onto the // second if the first command succeeded. chainCommand commandResult (fun () -> repeat command2 repeatData) if _inRepeatLastChange then _statusUtil.OnError Resources.NormalMode_RecursiveRepeatDetected CommandResult.Error else use bulkOperation = _bulkOperations.BeginBulkOperation() try _inRepeatLastChange <- true match _vimData.LastCommand with | None -> _commonOperations.Beep() CommandResult.Completed ModeSwitch.NoSwitch | Some command -> use transaction = _undoRedoOperations.CreateLinkedUndoTransactionWithFlags "Repeat Command" LinkedUndoTransactionFlags.CanBeEmpty let result = repeat command (Some repeatData) transaction.Complete() result finally _inRepeatLastChange <- false /// Repeat the last substitute command. member x.RepeatLastSubstitute useSameFlags useWholeBuffer = match _vimData.LastSubstituteData with | None -> _commonOperations.Beep() | Some data -> let range = if useWholeBuffer then SnapshotLineRangeUtil.CreateForSnapshot _textView.TextSnapshot else SnapshotLineRangeUtil.CreateForLine x.CaretLine let flags = if useSameFlags then data.Flags else SubstituteFlags.None _commonOperations.Substitute data.SearchPattern data.Substitute range flags CommandResult.Completed ModeSwitch.NoSwitch /// Replace the text at the caret via replace mode member x.ReplaceAtCaret count = let switch = ModeSwitch.SwitchModeWithArgument (ModeKind.Replace, ModeArgument.InsertWithCount count) CommandResult.Completed switch /// Replace the char under the cursor with the specified character member x.ReplaceChar keyInput count = let point = x.CaretPoint let line = point.GetContainingLine() let replaceChar () = let span = let endColumn = x.CaretColumn.AddInLineOrEnd count SnapshotColumnSpan(x.CaretColumn, endColumn) let position = if keyInput = KeyInputUtil.EnterKey then // Special case for replacement with a newline. First, vim only inserts a // single newline regardless of the count. Second, let the host do any magic // by simulating a keystroke, e.g. from inside a C# documentation comment. // The caret goes one character to the left of whereever it ended up _textBuffer.Delete(span.Span.Span) |> ignore _insertUtil.RunInsertCommand(InsertCommand.InsertNewLine) |> ignore let caretPoint = TextViewUtil.GetCaretPoint _textView caretPoint.Position - 1 else // The caret should move to the end of the replace operation which is // 'count - 1' characters from the original position let replaceText = new System.String(keyInput.Char, count) _textBuffer.Replace(span.Span.Span, replaceText) |> ignore point.Position + count - 1 // Don't use the ITextSnapshot that is returned from Replace. This represents the ITextSnapshot // after our change. If other components are listening to the Change events they could make their // own change. The ITextSnapshot returned reflects only our change, not theirs. To properly // position the caret we need the current ITextSnapshot let snapshot = _textBuffer.CurrentSnapshot // It's possible for any edit to occur after ours including the complete deletion of the buffer // contents. Need to account for this in the caret positioning. let position = min position snapshot.Length let point = SnapshotPoint(snapshot, position) let point = if SnapshotPointUtil.IsInsideLineBreak point then SnapshotPointUtil.GetNextPointWithWrap point else point TextViewUtil.MoveCaretToPoint _textView point // If the replace operation exceeds the line length then the operation // can't succeed if (point.Position + count) > line.End.Position then // If the replace failed then we should beep the console _commonOperations.Beep() CommandResult.Error else // Do the replace in an undo transaction since we are explicitly positioning // the caret x.EditWithUndoTransaction "ReplaceChar" (fun () -> replaceChar()) CommandResult.Completed ModeSwitch.NoSwitch /// Replace the char under the cursor in visual mode. member x.ReplaceSelection keyInput (visualSpan: VisualSpan) = let replaceText = if keyInput = KeyInputUtil.EnterKey then EditUtil.NewLine _options _textBuffer else System.String(keyInput.Char, 1) // First step is we want to update the selection. A replace char operation // in visual mode should position the caret on the first character and clear // the selection (both before and after). // // The caret can be anywhere at the start of the operation so move it to the // first point before even beginning the edit transaction TextViewUtil.ClearSelection _textView TextViewUtil.MoveCaretToPoint _textView visualSpan.Start x.EditWithUndoTransaction "ReplaceChar" (fun () -> use edit = _textBuffer.CreateEdit() let builder = System.Text.StringBuilder() for span in visualSpan.GetOverlapColumnSpans _localSettings.TabStop do if span.HasOverlapStart then let startColumn = span.Start builder.Length <- 0 builder.AppendCharCount ' ' startColumn.SpacesBefore builder.AppendStringCount replaceText (startColumn.TotalSpaces - startColumn.SpacesBefore) edit.Replace(startColumn.Column.Span.Span, (builder.ToString())) |> ignore span.InnerSpan.GetColumns SearchPath.Forward |> Seq.filter (fun column -> not column.IsLineBreakOrEnd) |> Seq.iter (fun column -> edit.Replace(column.Span.Span, replaceText) |> ignore) // Reposition the caret at the start of the edit let editPoint = x.ApplyEditAndMapPoint edit visualSpan.Start.Position TextViewUtil.MoveCaretToPoint _textView editPoint) CommandResult.Completed (ModeSwitch.SwitchMode ModeKind.Normal) /// Run the specified Command member x.RunCommand command = match command with | Command.NormalCommand (command, data) -> x.RunNormalCommand command data | Command.VisualCommand (command, data, visualSpan) -> x.RunVisualCommand command data visualSpan | Command.InsertCommand command -> x.RunInsertCommand command /// Run an 'at' command for the specified character member x.RunAtCommand char count = match char with | ':' -> // Repeat the last line command. let vim = _vimBufferData.Vim match vim.VimData.LastLineCommand with | None -> _commonOperations.Beep() | Some lastLineCommand -> match vim.GetVimBuffer _textView with | None -> _commonOperations.Beep() | Some vimBuffer -> let vimInterpreter = vim.GetVimInterpreter vimBuffer for i = 1 to count do vimInterpreter.RunLineCommand lastLineCommand | '@' -> // Repeat the last macro. match _vimData.LastMacroRun with | None -> _commonOperations.Beep() | Some registerName -> x.RunMacro registerName count | registerName -> // Run the macro with the specified register name. x.RunMacro registerName count CommandResult.Completed ModeSwitch.NoSwitch /// Run a macro using the contents of the specified register member x.RunMacro registerName count = let name = // TODO: Need to handle, = and . if CharUtil.IsDigit registerName then NumberedRegister.OfChar registerName |> Option.map RegisterName.Numbered elif registerName = '*' then SelectionAndDropRegister.Star |> RegisterName.SelectionAndDrop |> Some else let registerName = CharUtil.ToLower registerName NamedRegister.OfChar registerName |> Option.map RegisterName.Named match name with | None -> _commonOperations.Beep() | Some name -> let register = _registerMap.GetRegister name let list = register.RegisterValue.KeyInputs // The macro should be executed as a single action and the macro can execute in // several ITextBuffer instances (consider if the macros executes a 'gt' and keeps // editing). We need to have proper transactions for every ITextBuffer this macro // runs in // // Using .Net dictionary because we have to map by ITextBuffer which doesn't have // the comparison constraint let map = System.Collections.Generic.Dictionary<ITextBuffer, ILinkedUndoTransaction>(); use bulkOperation = _bulkOperations.BeginBulkOperation() try // Actually run the macro by replaying the key strokes one at a time. Returns // false if the macro should be stopped due to a failed command let runMacro () = let rec inner list = match list with | [] -> // No more input so we are finished true | keyInput :: tail -> // Prefer the focussed IVimBuffer over the current. It's possible for the // macro playback switch the active buffer via gt, gT, etc ... and playback // should continue on the newly focussed IVimBuffer. Should the host API // fail to return an active IVimBuffer continue using the original one let buffer = match _vim.FocusedBuffer with | Some buffer -> Some buffer | None -> _vim.GetVimBuffer _textView match buffer with | None -> // Nothing to do if we don't have an ITextBuffer with focus false | Some buffer -> // Make sure we have an IUndoTransaction open in the ITextBuffer if not (map.ContainsKey(buffer.TextBuffer)) then let transaction = _undoRedoOperations.CreateLinkedUndoTransactionWithFlags "Macro Run" LinkedUndoTransactionFlags.CanBeEmpty map.Add(buffer.TextBuffer, transaction) // Actually run the KeyInput. If processing the KeyInput value results // in an error then we should stop processing the macro match buffer.Process keyInput with | ProcessResult.Handled _ -> inner tail | ProcessResult.HandledNeedMoreInput -> inner tail | ProcessResult.NotHandled -> false | ProcessResult.Error -> false inner list // Run the macro count times. let go = ref true for i = 1 to count do if go.Value then go := runMacro() // Close out all of the transactions for transaction in map.Values do transaction.Complete() finally // Make sure to dispose the transactions in a finally block. Leaving them open // completely breaks undo in the ITextBuffer map.Values |> Seq.iter (fun transaction -> transaction.Dispose()) _vimData.LastMacroRun <- Some registerName /// Run a InsertCommand against the buffer member x.RunInsertCommand command = _insertUtil.RunInsertCommand command /// Run a NormalCommand against the buffer member x.RunNormalCommand command data = // Whether we should run the specified command for all carets. let shouldRunNormalCommandForEachCaret command = match command with | NormalCommand.AddToWord -> true | NormalCommand.ChangeMotion _ -> true | NormalCommand.ChangeCaseCaretLine _ -> true | NormalCommand.ChangeCaseCaretPoint _ -> true | NormalCommand.ChangeCaseMotion _ -> true | NormalCommand.ChangeLines -> true | NormalCommand.ChangeTillEndOfLine -> true | NormalCommand.DeleteCharacterAtCaret -> true | NormalCommand.DeleteCharacterBeforeCaret -> true | NormalCommand.DeleteLines -> true | NormalCommand.DeleteMotion _ -> true | NormalCommand.DeleteTillEndOfLine -> true | NormalCommand.FilterLines -> true | NormalCommand.FilterMotion _ -> true | NormalCommand.FormatCodeLines -> true | NormalCommand.FormatCodeMotion _ -> true | NormalCommand.FormatTextLines _ -> true | NormalCommand.FormatTextMotion _ -> true | NormalCommand.JoinLines _ -> true | NormalCommand.MoveCaretToMotion _ -> true | NormalCommand.PutAfterCaret _ -> true | NormalCommand.PutAfterCaretWithIndent -> true | NormalCommand.PutAfterCaretMouse -> true | NormalCommand.PutBeforeCaret _ -> true | NormalCommand.PutBeforeCaretWithIndent -> true | NormalCommand.RepeatLastCommand -> true | NormalCommand.RepeatLastSubstitute _ -> true | NormalCommand.ReplaceAtCaret -> true | NormalCommand.ReplaceChar _ -> true | NormalCommand.RunAtCommand _ -> true | NormalCommand.SubtractFromWord -> true | NormalCommand.ShiftLinesLeft -> true | NormalCommand.ShiftLinesRight -> true | NormalCommand.ShiftMotionLinesLeft _ -> true | NormalCommand.ShiftMotionLinesRight _ -> true | NormalCommand.SwitchModeVisualCommand visualKind -> match visualKind with | VisualKind.Character -> true | VisualKind.Line -> true | VisualKind.Block -> false | NormalCommand.SwitchToSelection _ -> true | NormalCommand.Yank _ -> true | _ -> false if shouldRunNormalCommandForEachCaret command then fun () -> x.RunNormalCommandCore command data |> _commonOperations.RunForAllSelections else x.RunNormalCommandCore command data /// Run a NormalCommand against the buffer member x.RunNormalCommandCore command (data: CommandData) = let registerName = data.RegisterName let count = data.CountOrDefault match command with | NormalCommand.AddCaretAtMousePoint -> x.AddCaretAtMousePoint() | NormalCommand.AddCaretOnAdjacentLine direction -> x.AddCaretOnAdjacentLine direction | NormalCommand.AddToWord -> x.AddToWord count | NormalCommand.CancelOperation -> x.CancelOperation() | NormalCommand.ChangeMotion motion -> x.RunWithMotion motion (x.ChangeMotion registerName) | NormalCommand.ChangeCaseCaretLine kind -> x.ChangeCaseCaretLine kind | NormalCommand.ChangeCaseCaretPoint kind -> x.ChangeCaseCaretPoint kind count | NormalCommand.ChangeCaseMotion (kind, motion) -> x.RunWithMotion motion (x.ChangeCaseMotion kind) | NormalCommand.ChangeLines -> x.ChangeLines count registerName | NormalCommand.ChangeTillEndOfLine -> x.ChangeTillEndOfLine count registerName | NormalCommand.CloseAllFolds -> x.CloseAllFolds() | NormalCommand.CloseAllFoldsUnderCaret -> x.CloseAllFoldsUnderCaret() | NormalCommand.CloseBuffer -> x.CloseBuffer() | NormalCommand.CloseWindow -> x.CloseWindow() | NormalCommand.CloseFoldUnderCaret -> x.CloseFoldUnderCaret count | NormalCommand.DeleteAllFoldsInBuffer -> x.DeleteAllFoldsInBuffer() | NormalCommand.DeleteAllFoldsUnderCaret -> x.DeleteAllFoldsUnderCaret() | NormalCommand.DeleteCharacterAtCaret -> x.DeleteCharacterAtCaret count registerName | NormalCommand.DeleteCharacterBeforeCaret -> x.DeleteCharacterBeforeCaret count registerName | NormalCommand.DeleteFoldUnderCaret -> x.DeleteFoldUnderCaret() | NormalCommand.DeleteLines -> x.DeleteLines count registerName | NormalCommand.DeleteMotion motion -> x.RunWithMotion motion (x.DeleteMotion registerName) | NormalCommand.DeleteTillEndOfLine -> x.DeleteTillEndOfLine count registerName | NormalCommand.DisplayCharacterBytes -> x.DisplayCharacterBytes() | NormalCommand.DisplayCharacterCodePoint -> x.DisplayCharacterCodePoint() | NormalCommand.FilterLines -> x.FilterLines count | NormalCommand.FilterMotion motion -> x.RunWithMotion motion x.FilterMotion | NormalCommand.FoldLines -> x.FoldLines data.CountOrDefault | NormalCommand.FoldMotion motion -> x.RunWithMotion motion x.FoldMotion | NormalCommand.FormatCodeLines -> x.FormatCodeLines count | NormalCommand.FormatCodeMotion motion -> x.RunWithMotion motion x.FormatCodeMotion | NormalCommand.FormatTextLines preserveCaretPosition -> x.FormatTextLines count preserveCaretPosition | NormalCommand.FormatTextMotion (preserveCaretPosition, motion) -> x.RunWithMotion motion (fun motion -> x.FormatTextMotion motion preserveCaretPosition) | NormalCommand.GoToDefinition -> x.GoToDefinition() | NormalCommand.GoToDefinitionUnderMouse -> x.GoToDefinitionUnderMouse() | NormalCommand.GoToFileUnderCaret useNewWindow -> x.GoToFileUnderCaret useNewWindow | NormalCommand.GoToGlobalDeclaration -> x.GoToGlobalDeclaration() | NormalCommand.GoToLocalDeclaration -> x.GoToLocalDeclaration() | NormalCommand.GoToNextTab path -> x.GoToNextTab path data.Count | NormalCommand.GoToWindow direction -> x.GoToWindow direction count | NormalCommand.GoToRecentView -> x.GoToRecentView count | NormalCommand.InsertAfterCaret -> x.InsertAfterCaret count | NormalCommand.InsertBeforeCaret -> x.InsertBeforeCaret count | NormalCommand.InsertAtEndOfLine -> x.InsertAtEndOfLine count | NormalCommand.InsertAtFirstNonBlank -> x.InsertAtFirstNonBlank count | NormalCommand.InsertAtStartOfLine -> x.InsertAtStartOfLine count | NormalCommand.InsertLineAbove -> x.InsertLineAbove count | NormalCommand.InsertLineBelow -> x.InsertLineBelow count | NormalCommand.JoinLines kind -> x.JoinLines kind count | NormalCommand.JumpToMark c -> x.JumpToMark c | NormalCommand.JumpToMarkLine c -> x.JumpToMarkLine c | NormalCommand.JumpToOlderPosition -> x.JumpToOlderPosition count | NormalCommand.JumpToNewerPosition -> x.JumpToNewerPosition count | NormalCommand.MoveCaretToMotion motion -> x.MoveCaretToMotion motion data.Count | NormalCommand.MoveCaretToMouse -> x.MoveCaretToMouse() | NormalCommand.NoOperation -> x.NoOperation() | NormalCommand.OpenAllFolds -> x.OpenAllFolds() | NormalCommand.OpenAllFoldsUnderCaret -> x.OpenAllFoldsUnderCaret() | NormalCommand.OpenLinkUnderCaret -> x.OpenLinkUnderCaret() | NormalCommand.OpenFoldUnderCaret -> x.OpenFoldUnderCaret data.CountOrDefault | NormalCommand.Ping pingData -> x.Ping pingData data | NormalCommand.PutAfterCaret moveCaretAfterText -> x.PutAfterCaret registerName count moveCaretAfterText | NormalCommand.PutAfterCaretWithIndent -> x.PutAfterCaretWithIndent registerName count | NormalCommand.PutAfterCaretMouse -> x.PutAfterCaretMouse() | NormalCommand.PutBeforeCaret moveCaretBeforeText -> x.PutBeforeCaret registerName count moveCaretBeforeText | NormalCommand.PutBeforeCaretWithIndent -> x.PutBeforeCaretWithIndent registerName count | NormalCommand.PrintFileInformation -> x.PrintFileInformation() | NormalCommand.RecordMacroStart c -> x.RecordMacroStart c | NormalCommand.RecordMacroStop -> x.RecordMacroStop() | NormalCommand.Redo -> x.Redo count | NormalCommand.RepeatLastCommand -> x.RepeatLastCommand data | NormalCommand.RepeatLastSubstitute (useSameFlags, useWholeBuffer) -> x.RepeatLastSubstitute useSameFlags useWholeBuffer | NormalCommand.ReplaceAtCaret -> x.ReplaceAtCaret count | NormalCommand.ReplaceChar keyInput -> x.ReplaceChar keyInput data.CountOrDefault | NormalCommand.RestoreMultiSelection -> x.RestoreMultiSelection() | NormalCommand.RunAtCommand char -> x.RunAtCommand char data.CountOrDefault | NormalCommand.SetMarkToCaret c -> x.SetMarkToCaret c | NormalCommand.ScrollLines (direction, useScrollOption) -> x.ScrollLines direction useScrollOption data.Count | NormalCommand.ScrollPages direction -> x.ScrollPages direction data.CountOrDefault | NormalCommand.ScrollWindow direction -> x.ScrollWindow direction count | NormalCommand.ScrollCaretLineToTop keepCaretColumn -> x.ScrollCaretLineToTop keepCaretColumn | NormalCommand.ScrollCaretLineToMiddle keepCaretColumn -> x.ScrollCaretLineToMiddle keepCaretColumn | NormalCommand.ScrollCaretLineToBottom keepCaretColumn -> x.ScrollCaretLineToBottom keepCaretColumn | NormalCommand.ScrollCaretColumnToLeft -> x.ScrollCaretColumnToLeft() | NormalCommand.ScrollCaretColumnToRight -> x.ScrollCaretColumnToRight() | NormalCommand.ScrollColumns direction -> x.ScrollColumns direction count | NormalCommand.ScrollHalfWidth direction -> x.ScrollHalfWidth direction | NormalCommand.SelectBlock -> x.SelectBlock() | NormalCommand.SelectLine -> x.SelectLine() | NormalCommand.SelectNextMatch searchPath -> x.SelectNextMatch searchPath data.Count | NormalCommand.SelectTextForMouseClick -> x.SelectTextForMouseClick() | NormalCommand.SelectTextForMouseDrag -> x.SelectTextForMouseDrag() | NormalCommand.SelectTextForMouseRelease -> x.SelectTextForMouseRelease() | NormalCommand.SelectWordOrMatchingToken -> x.SelectWordOrMatchingToken() | NormalCommand.SelectWordOrMatchingTokenAtMousePoint -> x.SelectWordOrMatchingTokenAtMousePoint() | NormalCommand.SubstituteCharacterAtCaret -> x.SubstituteCharacterAtCaret count registerName | NormalCommand.SubtractFromWord -> x.SubtractFromWord count | NormalCommand.ShiftLinesLeft -> x.ShiftLinesLeft count | NormalCommand.ShiftLinesRight -> x.ShiftLinesRight count | NormalCommand.ShiftMotionLinesLeft motion -> x.RunWithMotion motion x.ShiftMotionLinesLeft | NormalCommand.ShiftMotionLinesRight motion -> x.RunWithMotion motion x.ShiftMotionLinesRight | NormalCommand.SplitViewHorizontally -> x.SplitViewHorizontally() | NormalCommand.SplitViewVertically -> x.SplitViewVertically() | NormalCommand.SwitchMode (modeKind, modeArgument) -> x.SwitchMode modeKind modeArgument | NormalCommand.SwitchModeVisualCommand visualKind -> x.SwitchModeVisualCommand visualKind data.Count | NormalCommand.SwitchPreviousVisualMode -> x.SwitchPreviousVisualMode() | NormalCommand.SwitchToSelection caretMovement -> x.SwitchToSelection caretMovement | NormalCommand.ToggleFoldUnderCaret -> x.ToggleFoldUnderCaret count | NormalCommand.ToggleAllFolds -> x.ToggleAllFolds() | NormalCommand.Undo -> x.Undo count | NormalCommand.UndoLine -> x.UndoLine() | NormalCommand.WriteBufferAndQuit -> x.WriteBufferAndQuit() | NormalCommand.Yank motion -> x.RunWithMotion motion (x.YankMotion registerName) | NormalCommand.YankLines -> x.YankLines count registerName /// The visual span associated with the selection member x.GetVisualSpan visualKind = let tabStop = _localSettings.TabStop let useVirtualSpace = _vimBufferData.VimTextBuffer.UseVirtualSpace VisualSpan.CreateForVirtualSelection _textView visualKind tabStop useVirtualSpace /// Run a VisualCommand against the buffer member x.RunVisualCommand command data visualSpan = // Whether we should run the specified visual command for each selection let shouldRunVisualCommandForEachSelection command visualKind = match visualKind with | VisualKind.Character | VisualKind.Line -> match command with | VisualCommand.AddToSelection _ -> true | VisualCommand.ChangeCase _ -> true | VisualCommand.ChangeSelection -> true | VisualCommand.DeleteSelection -> true | VisualCommand.InvertSelection _ -> true | VisualCommand.MoveCaretToTextObject _-> true | VisualCommand.PutOverSelection _ -> true | VisualCommand.ReplaceSelection _ -> true | VisualCommand.SelectLine -> true | VisualCommand.ShiftLinesLeft -> true | VisualCommand.ShiftLinesRight -> true | VisualCommand.SubtractFromSelection _ -> true | VisualCommand.CutSelection -> true | VisualCommand.CutSelectionAndPaste -> true | _ -> false | VisualKind.Block -> false if shouldRunVisualCommandForEachSelection command visualSpan.VisualKind then fun () -> x.GetVisualSpan visualSpan.VisualKind |> x.RunVisualCommandCore command data |> _commonOperations.RunForAllSelections else x.RunVisualCommandCore command data visualSpan /// Run a VisualCommand against the buffer member x.RunVisualCommandCore command (data: CommandData) (visualSpan: VisualSpan) = /// Whether we should clear the selection before running the command let shouldClearSelection command = match command with | VisualCommand.AddCaretAtMousePoint -> false | VisualCommand.AddSelectionOnAdjacentLine _ -> false | VisualCommand.CutSelection -> false | VisualCommand.CopySelection -> false | VisualCommand.CutSelectionAndPaste -> false | VisualCommand.InvertSelection _ -> false | VisualCommand.AddWordOrMatchingTokenAtMousePointToSelection -> false - | VisualCommand.AddNextOccurrenceOfPrimarySelection -> false + | VisualCommand.StartMultiSelection -> false | _ -> true // Maybe clear the selection before actually running any Visual // Commands. Selection is one of the items which is preserved along // with caret position when we use an edit transaction with the change // primitives (EditWithUndoTransaction). We don't want the selection // to reappear during an undo hence clear it now so it's gone. if shouldClearSelection command then TextViewUtil.ClearSelection _textView let registerName = data.RegisterName let count = data.CountOrDefault match command with | VisualCommand.AddCaretAtMousePoint -> x.AddCaretAtMousePoint() - | VisualCommand.AddNextOccurrenceOfPrimarySelection -> x.AddNextOccurrenceOfPrimarySelection data.Count | VisualCommand.AddSelectionOnAdjacentLine direction -> x.AddSelectionOnAdjacentLine direction | VisualCommand.AddToSelection isProgressive -> x.AddToSelection visualSpan count isProgressive | VisualCommand.AddWordOrMatchingTokenAtMousePointToSelection -> x.AddWordOrMatchingTokenAtMousePointToSelection() | VisualCommand.CancelOperation -> x.CancelOperation() | VisualCommand.ChangeCase kind -> x.ChangeCaseVisual kind visualSpan | VisualCommand.ChangeSelection -> x.ChangeSelection registerName visualSpan | VisualCommand.CloseAllFoldsInSelection -> x.CloseAllFoldsInSelection visualSpan | VisualCommand.CloseFoldInSelection -> x.CloseFoldInSelection visualSpan | VisualCommand.ChangeLineSelection specialCaseBlock -> x.ChangeLineSelection registerName visualSpan specialCaseBlock | VisualCommand.DeleteAllFoldsInSelection -> x.DeleteAllFoldInSelection visualSpan | VisualCommand.DeleteSelection -> x.DeleteSelection registerName visualSpan | VisualCommand.DeleteLineSelection -> x.DeleteLineSelection registerName visualSpan | VisualCommand.ExtendSelectionForMouseClick -> x.ExtendSelectionForMouseClick() | VisualCommand.ExtendSelectionForMouseDrag -> x.ExtendSelectionForMouseDrag visualSpan | VisualCommand.ExtendSelectionForMouseRelease -> x.ExtendSelectionForMouseRelease visualSpan | VisualCommand.ExtendSelectionToNextMatch searchPath -> x.ExtendSelectionToNextMatch searchPath data.Count | VisualCommand.FilterLines -> x.FilterLinesVisual visualSpan | VisualCommand.FormatCodeLines -> x.FormatCodeLinesVisual visualSpan | VisualCommand.FormatTextLines preserveCaretPosition -> x.FormatTextLinesVisual visualSpan preserveCaretPosition | VisualCommand.FoldSelection -> x.FoldSelection visualSpan | VisualCommand.GoToFileInSelectionInNewWindow -> x.GoToFileInSelectionInNewWindow visualSpan | VisualCommand.GoToFileInSelection -> x.GoToFileInSelection visualSpan | VisualCommand.JoinSelection kind -> x.JoinSelection kind visualSpan | VisualCommand.InvertSelection columnOnlyInBlock -> x.InvertSelection visualSpan columnOnlyInBlock | VisualCommand.MoveCaretToMouse -> x.MoveCaretToMouse() | VisualCommand.MoveCaretToTextObject (motion, textObjectKind)-> x.MoveCaretToTextObject count motion textObjectKind visualSpan | VisualCommand.OpenFoldInSelection -> x.OpenFoldInSelection visualSpan | VisualCommand.OpenAllFoldsInSelection -> x.OpenAllFoldsInSelection visualSpan | VisualCommand.OpenLinkInSelection -> x.OpenLinkInSelection visualSpan | VisualCommand.PutOverSelection moveCaretAfterText -> x.PutOverSelection registerName count moveCaretAfterText visualSpan | VisualCommand.ReplaceSelection keyInput -> x.ReplaceSelection keyInput visualSpan | VisualCommand.SelectBlock -> x.SelectBlock() | VisualCommand.SelectLine -> x.SelectLine() | VisualCommand.SelectWordOrMatchingTokenAtMousePoint -> x.SelectWordOrMatchingTokenAtMousePoint() | VisualCommand.ShiftLinesLeft -> x.ShiftLinesLeftVisual count visualSpan | VisualCommand.ShiftLinesRight -> x.ShiftLinesRightVisual count visualSpan - | VisualCommand.SplitSelectionIntoCarets -> x.SplitSelectionIntoCarets visualSpan + | VisualCommand.StartMultiSelection -> x.StartMultiSelection data.Count visualSpan | VisualCommand.SubtractFromSelection isProgressive -> x.SubtractFromSelection visualSpan count isProgressive | VisualCommand.SwitchModeInsert atEndOfLine -> x.SwitchModeInsert visualSpan atEndOfLine | VisualCommand.SwitchModePrevious -> x.SwitchPreviousMode() | VisualCommand.SwitchModeVisual visualKind -> x.SwitchModeVisual visualKind | VisualCommand.SwitchModeOtherVisual -> x.SwitchModeOtherVisual visualSpan | VisualCommand.ToggleFoldInSelection -> x.ToggleFoldUnderCaret count | VisualCommand.ToggleAllFoldsInSelection-> x.ToggleAllFolds() | VisualCommand.YankLineSelection -> x.YankLineSelection registerName visualSpan | VisualCommand.YankSelection -> x.YankSelection registerName visualSpan | VisualCommand.CutSelection -> x.CutSelection() | VisualCommand.CopySelection -> x.CopySelection() | VisualCommand.CutSelectionAndPaste -> x.CutSelectionAndPaste() | VisualCommand.SelectAll -> x.SelectAll() /// Get the MotionResult value for the provided MotionData and pass it /// if found to the provided function member x.RunWithMotion (motion: MotionData) func = match _motionUtil.GetMotion motion.Motion motion.MotionArgument with | None -> _commonOperations.Beep() CommandResult.Error | Some data -> func data /// Process the m[a-z] command member x.SetMarkToCaret c = match Mark.OfChar c with | None -> _statusUtil.OnError Resources.Common_MarkInvalid _commonOperations.Beep() CommandResult.Error | Some mark -> let lineNumber, offset = VirtualSnapshotPointUtil.GetLineNumberAndOffset x.CaretVirtualPoint if not (_markMap.SetMark mark _vimBufferData lineNumber offset) then // Mark set can fail if the user chooses a readonly mark like '<' _commonOperations.Beep() CommandResult.Completed ModeSwitch.NoSwitch /// Get the number lines in the current window member x.GetWindowLineCount (textViewLines: ITextViewLineCollection) = let lineHeight = _textView.LineHeight let viewportHeight = _textView.ViewportHeight int (floor (viewportHeight / lineHeight)) /// Scroll viewport of the current text view vertically by lines member x.ScrollViewportVerticallyByLines (scrollDirection: ScrollDirection) (count: int) = if count = 1 then _textView.ViewScroller.ScrollViewportVerticallyByLine(scrollDirection) else // Avoid using 'ScrollViewportVerticallyByLines' because it forces // a layout for every line scrolled. Normally this is not a serious // problem but on some displays the layout costs are so high that // the operation becomes pathologically slow. See issue #1633. let sign = if scrollDirection = ScrollDirection.Up then 1 else -1 let pixels = float(sign * count) * _textView.LineHeight _textView.ViewScroller.ScrollViewportVerticallyByPixels(pixels) /// Scroll the window horizontally by the specified number of pixels member x.ScrollHorizontallyByPixels pixels = _textView.ViewScroller.ScrollViewportHorizontallyByPixels(pixels) /// Get the caret text view line unless line wrap is enabled member x.CaretTextViewLineUnlessWrap () = match TextViewUtil.IsWordWrapEnabled _textView with | false -> TextViewUtil.GetTextViewLineContainingCaret _textView | true -> None /// Move the caret horizontally into the viewport member x.MoveCaretHorizontallyIntoViewport () = // Move the caret without checking visibility. let moveCaretToPoint (point: SnapshotPoint) = TextViewUtil.MoveCaretToPointRaw _textView point MoveCaretFlags.None match x.CaretTextViewLineUnlessWrap() with | Some textViewLine -> // Check whether the caret is within the viewport. let caretBounds = x.CaretVirtualPoint |> textViewLine.GetCharacterBounds if caretBounds.Left < _textView.ViewportLeft then TextViewUtil.GetVisibleSpan _textView textViewLine |> SnapshotSpanUtil.GetStartPoint |> moveCaretToPoint elif caretBounds.Right > _textView.ViewportRight then TextViewUtil.GetVisibleSpan _textView textViewLine |> SnapshotSpanUtil.GetEndPoint |> moveCaretToPoint | None -> () /// Scroll the window horizontally so that the caret is at the left edge /// of the screen member x.ScrollCaretColumnToLeft () = match x.CaretTextViewLineUnlessWrap() with | Some textViewLine -> let caretBounds = textViewLine.GetCharacterBounds(x.CaretVirtualPoint) let xStart = _textView.ViewportLeft let xCaret = caretBounds.Left xCaret - xStart |> x.ScrollHorizontallyByPixels | None -> () CommandResult.Completed ModeSwitch.NoSwitch /// Scroll the window horizontally so that the caret is at the right edge /// of the screen member x.ScrollCaretColumnToRight () = match x.CaretTextViewLineUnlessWrap() with | Some textViewLine -> let caretBounds = textViewLine.GetCharacterBounds(x.CaretVirtualPoint) let xEnd = _textView.ViewportRight let xCaret = caretBounds.Right xCaret - xEnd |> x.ScrollHorizontallyByPixels | None -> () CommandResult.Completed ModeSwitch.NoSwitch /// Scroll the window horizontally in the specified direction member x.ScrollColumns direction count = match x.CaretTextViewLineUnlessWrap() with | Some textViewLine -> let spaceWidth = textViewLine.VirtualSpaceWidth let pixels = double(count) * spaceWidth let pixels = match direction with | Direction.Left -> -pixels | Direction.Right -> pixels | _ -> 0.0 x.ScrollHorizontallyByPixels pixels x.MoveCaretHorizontallyIntoViewport() | None -> () CommandResult.Completed ModeSwitch.NoSwitch /// Scroll half the width of the window in the specified direction member x.ScrollHalfWidth direction = match x.CaretTextViewLineUnlessWrap() with | Some textViewLine -> let spaceWidth = textViewLine.VirtualSpaceWidth let columns = _textView.ViewportWidth / spaceWidth let count = int(round(columns / 2.0)) x.ScrollColumns direction count | None -> CommandResult.Completed ModeSwitch.NoSwitch /// Scroll the window up / down a specified number of lines. If a count is provided /// that will always be used. Else we may choose one or the value of the 'scroll' /// option member x.ScrollLines scrollDirection useScrollOption countOption = // Scrolling lines needs to scroll against the visual buffer vs the edit buffer so // that we treated folded lines as a single line. Normally this would mean we need // to jump into the Visual Snapshot. Here we don't though because we end using // IViewScroller to scroll and it does it's count based on Visual Lines vs. real lines // in the edit buffer // Get the number of lines that we should scroll by. let count = match countOption with | Some count -> // When a count is provided then we always use that count. If this is a // scroll option version though we do need to update the scroll option to // this value if useScrollOption then _windowSettings.Scroll <- count count | None -> if useScrollOption then _windowSettings.Scroll else 1 // Ensure that we scroll by at least one line. let minCount = 1 let count = max count minCount let spacesToCaret = _commonOperations.GetSpacesToCaret() // Update the caret to the specified offset from the first visible line if possible let updateCaretToOffset lineOffset = match TextViewUtil.GetTextViewLines _textView with | None -> () | Some textViewLines -> let firstIndex = textViewLines.GetIndexOfTextLine(textViewLines.FirstVisibleLine) let caretIndex = firstIndex + lineOffset if caretIndex >= 0 && caretIndex < textViewLines.Count then let textViewLine = textViewLines.[caretIndex] let snapshotLine = SnapshotPointUtil.GetContainingLine textViewLine.Start _commonOperations.MoveCaretToPoint snapshotLine.Start ViewFlags.Standard let textViewLines = TextViewUtil.GetTextViewLines _textView let caretTextViewLine = TextViewUtil.GetTextViewLineContainingCaret _textView match textViewLines, caretTextViewLine with | Some textViewLines, Some caretTextViewLine -> // Limit the amount of scrolling to the size of the window. let maxCount = x.GetWindowLineCount textViewLines let count = min count maxCount let firstIndex = textViewLines.GetIndexOfTextLine(textViewLines.FirstVisibleLine) let caretIndex = textViewLines.GetIndexOfTextLine(caretTextViewLine) // How many visual lines is the caret offset from the first visible line let lineOffset = max 0 (caretIndex - firstIndex) match scrollDirection with | ScrollDirection.Up -> if 0 = textViewLines.FirstVisibleLine.Start.Position then // The buffer is currently scrolled to the very top. Move the caret by the specified // count or beep if caret at the start of the file as well. Make sure this movement // occurs on the visual lines, not the edit buffer (other wise folds will cause the // caret to move incorrectly) if caretIndex = 0 then _commonOperations.Beep() else let index = max 0 (caretIndex - count) let line = textViewLines.[index] TextViewUtil.MoveCaretToPoint _textView line.Start else x.ScrollViewportVerticallyByLines scrollDirection count updateCaretToOffset lineOffset | ScrollDirection.Down -> let lastLine = SnapshotUtil.GetLastNormalizedLine _textView.TextSnapshot let visualEndPoint = lastLine.End if visualEndPoint.Position <= textViewLines.LastVisibleLine.End.Position then // Currently scrolled to the end of the buffer. Move the caret by the count or // beep if truly at the end let lastIndex = textViewLines.GetIndexOfTextLine(textViewLines.LastVisibleLine) if lastIndex = caretIndex then _commonOperations.Beep() else let index = min (textViewLines.Count - 1) (caretIndex + count) let line = textViewLines.[index] let caretPoint, _ = SnapshotPointUtil.OrderAscending visualEndPoint line.End TextViewUtil.MoveCaretToPoint _textView caretPoint else x.ScrollViewportVerticallyByLines scrollDirection count updateCaretToOffset lineOffset | _ -> () // First apply scroll offset. _commonOperations.AdjustCaretForScrollOffset() // At this point the view has been scrolled and the caret is on the // proper line. Need to adjust the caret within the line to the // appropriate column. _commonOperations.RestoreSpacesToCaret spacesToCaret true | _ -> () CommandResult.Completed ModeSwitch.NoSwitch /// Scroll pages in the specified direction member x.ScrollPages direction count = // Get whether this scroll is up or down. let getIsUp direction = match direction with | ScrollDirection.Up -> Some true | ScrollDirection.Down -> Some false | _ -> None // Get the page scroll amount in lines, allowing for /// some overlapping context lines (vim overlaps two). let getScrollAmount (textViewLines: ITextViewLineCollection) = let lineCount = x.GetWindowLineCount textViewLines max 1 (lineCount - 2) // Scroll up by one full page unless we are at the top. let doScrollUp () = match TextViewUtil.GetTextViewLines _textView with | None -> _editorOperations.PageUp(false) | Some textViewLines -> let scrollAmount = getScrollAmount textViewLines x.ScrollViewportVerticallyByLines ScrollDirection.Up scrollAmount // Scroll down by one full page or as much as possible. let doScrollDown () = match TextViewUtil.GetTextViewLines _textView with | None -> _editorOperations.PageDown(false) | Some textViewLines -> // Check whether the last line is visible. let lastVisiblePoint = textViewLines.LastVisibleLine.EndIncludingLineBreak let lastVisibleLine = SnapshotPointUtil.GetContainingLine lastVisiblePoint let lastVisibleLineNumber = lastVisibleLine.LineNumber let lastLine = SnapshotUtil.GetLastNormalizedLine _textView.TextSnapshot let lastLineNumber = SnapshotLineUtil.GetLineNumber lastLine if lastVisibleLineNumber >= lastLineNumber then // The last line is already visible. Move the caret // to the last line and scroll it to the top of the view. TextViewUtil.MoveCaretToPointRaw _textView lastLine.Start MoveCaretFlags.None _editorOperations.ScrollLineTop() else let scrollAmount = getScrollAmount textViewLines x.ScrollViewportVerticallyByLines ScrollDirection.Down scrollAmount // Get the last (and if possible, fully visible) line in the text view. let getLastFullyVisibleLine (textViewLines: ITextViewLineCollection) = let lastLine = textViewLines.LastVisibleLine if lastLine.VisibilityState = Formatting.VisibilityState.FullyVisible then lastLine else // The last line is only partially visible. This could be // either because the view is scrolled so that the bottom of // the text row is clipped, or because line wrapping is in // effect and there are off-screen wrapped text view lines. In // either case, try to move to the text view line corresponding // to the previous snapshot line. let partialLine = SnapshotPointUtil.GetContainingLine lastLine.Start let previousLineNumber = partialLine.LineNumber - 1 let previousLine = SnapshotUtil.GetLineOrFirst _textView.TextSnapshot previousLineNumber match TextViewUtil.GetTextViewLineContainingPoint _textView previousLine.Start with | Some textViewLine when textViewLine.VisibilityState = Formatting.VisibilityState.FullyVisible -> textViewLine | _ -> lastLine let spacesToCaret = _commonOperations.GetSpacesToCaret() match getIsUp direction with | None -> _commonOperations.Beep() | Some isUp -> // Do the scrolling. for i = 1 to count do if isUp then doScrollUp() else doScrollDown() // Adjust the caret by, roughly, putting the cursor on the // first non-blank character of the last visible line // when scrolling up, and on the first non-blank character // of the first visible line when scrolling down. match TextViewUtil.GetTextViewLines _textView with | None -> () | Some textViewLines -> // Find a text view line belonging to the snapshot line that // should contain the caret. let textViewLine = if isUp then // As a special case when scrolling up, if the caret // line is already visible on the screen, use that line. match TextViewUtil.GetTextViewLineContainingCaret _textView with | Some caretLine when caretLine.VisibilityState = VisibilityState.FullyVisible -> caretLine | _ -> getLastFullyVisibleLine textViewLines else textViewLines.FirstVisibleLine // Find the snapshot line corresponding to the text view line. let line = SnapshotPointUtil.GetContainingLine textViewLine.Start // Move the caret to the beginning of that line. TextViewUtil.MoveCaretToPointRaw _textView line.Start MoveCaretFlags.None // First apply scroll offset. _commonOperations.AdjustCaretForScrollOffset() // At this point the view has been scrolled and the caret is on // the proper line. Need to adjust the caret within the line // to the appropriate column. _commonOperations.RestoreSpacesToCaret spacesToCaret true CommandResult.Completed ModeSwitch.NoSwitch /// Scroll the window in the specified direction by the specified number of lines. The /// caret only moves if it leaves the view port member x.ScrollWindow direction count = // Count the number of rows we need to scroll to move count // lines off the screen in the specified direction. let rowCount = if not (TextViewUtil.IsWordWrapEnabled _textView) then count else // If line wrapping is in effect, there can be multiple screen rows // corrsponding to a single text buffer line. match TextViewUtil.GetTextViewLines _textView with | None -> count | Some textViewLines -> // Build an array of the text view line indexes that correspond // to the first segment of a fully visible text buffer line. // These are the rows that have a line number next to them // when line numbering is turned on. let numberedLineIndexes = textViewLines |> Seq.where (fun textViewLine -> textViewLine.VisibilityState = Formatting.VisibilityState.FullyVisible && textViewLine.Start = textViewLine.Start.GetContainingLine().Start) |> Seq.map (fun textViewLine -> textViewLines.GetIndexOfTextLine(textViewLine)) |> Seq.toArray let lastNumberedLineIndex = numberedLineIndexes.Length - 1 // Use the numbered line indexes to count screen rows used by // lines visible in the text view. if count <= lastNumberedLineIndex then match direction with | ScrollDirection.Up -> // Calculate how many rows the last fully visible line uses. let rec getWrapCount (index: int) = if index <= textViewLines.Count - 2 then // Does the current text view line belong to the same // text buffer line as the next text view line? let currentLine = textViewLines.[index].Start.GetContainingLine() let nextLine = textViewLines.[index + 1].Start.GetContainingLine() if currentLine.LineNumber = nextLine.LineNumber then let wrapCount = getWrapCount (index + 1) wrapCount + 1 else 1 else 1 let lastIndex = numberedLineIndexes.[lastNumberedLineIndex] let targetIndex = numberedLineIndexes.[lastNumberedLineIndex - (count - 1)] let lastWrapCount = getWrapCount lastIndex lastIndex - targetIndex + lastWrapCount | ScrollDirection.Down -> let firstIndex = numberedLineIndexes.[0] let targetIndex = numberedLineIndexes.[count] targetIndex - firstIndex | _ -> count else count // In case something went wrong when calculating the row count, // it should always be at least at big as count. let rowCount = max rowCount count let spacesToCaret = _commonOperations.GetSpacesToCaret() x.ScrollViewportVerticallyByLines direction rowCount match TextViewUtil.GetVisibleSnapshotLineRange _textView with | None -> () | Some lineRange -> match direction with | ScrollDirection.Up -> if x.CaretPoint.Position > lineRange.End.Position then TextViewUtil.MoveCaretToPoint _textView lineRange.End | ScrollDirection.Down -> if x.CaretPoint.Position < lineRange.Start.Position then TextViewUtil.MoveCaretToPoint _textView lineRange.Start | _ -> () // First apply scroll offset. _commonOperations.AdjustCaretForScrollOffset() // At this point the view has been scrolled and the caret is on the // proper line. Need to adjust the caret within the line to the // appropriate column. _commonOperations.RestoreSpacesToCaret spacesToCaret false CommandResult.Completed ModeSwitch.NoSwitch /// Scroll the line containing the caret to the top of the ITextView. member x.ScrollCaretLineToTop keepCaretColumn = _commonOperations.EditorOperations.ScrollLineTop() if not keepCaretColumn then _commonOperations.EditorOperations.MoveToStartOfLineAfterWhiteSpace(false) _commonOperations.EnsureAtCaret ViewFlags.ScrollOffset CommandResult.Completed ModeSwitch.NoSwitch /// Scroll the line containing the caret to the middle of the ITextView. member x.ScrollCaretLineToMiddle keepCaretColumn = _commonOperations.EditorOperations.ScrollLineCenter() if not keepCaretColumn then _commonOperations.EditorOperations.MoveToStartOfLineAfterWhiteSpace(false) _commonOperations.EnsureAtCaret ViewFlags.ScrollOffset CommandResult.Completed ModeSwitch.NoSwitch /// Scroll the line containing the caret to the bottom of the ITextView. member x.ScrollCaretLineToBottom keepCaretColumn = _commonOperations.EditorOperations.ScrollLineBottom() if not keepCaretColumn then _commonOperations.EditorOperations.MoveToStartOfLineAfterWhiteSpace(false) _commonOperations.EnsureAtCaret ViewFlags.ScrollOffset CommandResult.Completed ModeSwitch.NoSwitch /// Select the current block member x.SelectBlock () = x.MoveCaretToMouseUnconditionally() |> ignore let visualKind = VisualKind.Block let startPoint = x.CaretPoint let endPoint = x.CaretPoint let tabStop = _localSettings.TabStop let visualSelection = VisualSelection.CreateForPoints visualKind startPoint endPoint tabStop x.SwitchModeVisualOrSelect SelectModeOptions.Mouse visualSelection (Some startPoint) /// Select the current line member x.SelectLine () = x.MoveCaretToMouseUnconditionally() |> ignore let visualKind = VisualKind.Line let startPoint = x.CaretPoint let endPoint = x.CaretPoint let tabStop = _localSettings.TabStop let visualSelection = VisualSelection.CreateForPoints visualKind startPoint endPoint tabStop x.SwitchModeVisualOrSelect SelectModeOptions.Mouse visualSelection (Some startPoint) /// Select the next match for the last pattern searched for member x.SelectNextMatch searchPath count = let motion = Motion.NextMatch searchPath let argument = MotionArgument(MotionContext.Movement, operatorCount = None, motionCount = count) match _motionUtil.GetMotion motion argument with | Some motionResult -> let visualKind = VisualKind.Character let startPoint = motionResult.Span.Start let endPoint = if motionResult.Span.Length > 0 then motionResult.Span.End |> SnapshotPointUtil.GetPreviousCharacterSpanWithWrap else motionResult.Span.End let tabStop = _localSettings.TabStop let visualSelection = VisualSelection.CreateForPoints visualKind startPoint endPoint tabStop x.SwitchModeVisualOrSelect SelectModeOptions.Command visualSelection None | None -> CommandResult.Completed ModeSwitch.NoSwitch /// Select text for a mouse click member x.SelectTextForMouseClick () = let startPoint = x.CaretPoint x.MoveCaretToMouseUnconditionally() |> ignore x.SelectTextCore startPoint /// Select text for a mouse drag member x.SelectTextForMouseDrag () = // A click with the mouse to position the caret may be followed by a // slight jiggle of the mouse position, which will cause a drag event. // Prevent accidentally switching to select mode by requiring the caret // to move to a new snapshot point. In addition, the current caret // position may not agree with the mouse pointer if the mouse was // clicked past the end of the line and the caret was moved back due to // virtual edit settings. In both cases we refer to the where the // mouse was clicked, not where the caret ends up. match x.LeftMouseDownPoint with | Some startPoint -> if x.MoveCaretToMouseIfChanged() then x.SelectTextCore startPoint.Position else CommandResult.Completed ModeSwitch.NoSwitch | None -> CommandResult.Error /// Select text for a mouse release member x.SelectTextForMouseRelease () = let result = x.SelectTextForMouseDrag() x.HandleMouseRelease() result member x.SelectTextCore startPoint = let endPoint = x.CaretPoint let visualKind = VisualKind.Character let tabStop = _localSettings.TabStop let visualSelection = VisualSelection.CreateForPoints visualKind startPoint endPoint tabStop let visualSelection = visualSelection.AdjustForSelectionKind _globalSettings.SelectionKind x.SwitchModeVisualOrSelect SelectModeOptions.Mouse visualSelection (Some startPoint) /// Get the word or matching token under the mouse member x.GetWordOrMatchingToken () = let text = x.CaretPoint |> SnapshotPointUtil.GetCharacterSpan |> SnapshotSpanUtil.GetText let result, isToken = let isWord = text.Length = 1 && _wordUtil.IsKeywordChar text.[0] let argument = MotionArgument(MotionContext.Movement) let motion = Motion.MatchingTokenOrDocumentPercent match isWord, _motionUtil.GetMotion motion argument with | false, Some motionResult -> Some motionResult, true | _ -> let motion = Motion.InnerWord WordKind.NormalWord match _motionUtil.GetMotion motion argument with | Some motionResult -> _doSelectByWord <- true Some motionResult, false | None -> None, false match result with | Some motionResult -> let startPoint = motionResult.Span.Start let endPoint = if motionResult.Span.Length > 0 then motionResult.Span.End |> SnapshotPointUtil.GetPreviousCharacterSpanWithWrap else motionResult.Span.End let visualKind = match isToken, text with | true, "#" -> VisualKind.Line | _ -> VisualKind.Character let tabStop = _localSettings.TabStop VisualSelection.CreateForPoints visualKind startPoint endPoint tabStop |> Some | None -> None // Explicitly set a single caret or selection so that the multi-selection // tracker doesn't restore any secondary selections member x.ClearSecondarySelections () = [_commonOperations.PrimarySelectedSpan] |> _commonOperations.SetSelectedSpans /// Select the word or matching token at the mouse point member x.SelectWordOrMatchingTokenAtMousePoint () = x.MoveCaretToMouseUnconditionally() |> ignore x.SelectWordOrMatchingTokenCore SelectModeOptions.Mouse /// Add word or matching token at the current mouse point to the selection member x.AddWordOrMatchingTokenAtMousePointToSelection () = let oldSelectedSpans = _commonOperations.SelectedSpans let contains = VirtualSnapshotSpanUtil.ContainsOrEndsWith x.MoveCaretToMouseUnconditionally() |> ignore match x.GetWordOrMatchingToken() with | Some visualSelection -> let newSelectedSpan = _globalSettings.SelectionKind |> visualSelection.GetPrimarySelectedSpan // One of the old spans will contain the secondary caret // added by the first click. Remove it and add a new one. let oldSelectedSpans = oldSelectedSpans |> Seq.filter (fun span -> not (contains newSelectedSpan.Span span.CaretPoint)) seq { yield! oldSelectedSpans yield newSelectedSpan } |> _commonOperations.SetSelectedSpans CommandResult.Completed ModeSwitch.NoSwitch | None -> CommandResult.Error /// Select the word or matching token under the caret member x.SelectWordOrMatchingToken () = x.SelectWordOrMatchingTokenCore SelectModeOptions.Command /// Select the word or matching token under the caret and switch to mode /// appropriate for the specified select mode options member x.SelectWordOrMatchingTokenCore selectModeOptions = match x.GetWordOrMatchingToken() with | Some visualSelection -> x.ClearSecondarySelections() x.SwitchModeVisualOrSelect selectModeOptions visualSelection None | None -> CommandResult.Error + /// Add the next occurrence of the primary selection or split the + /// selection into carets + member x.StartMultiSelection count visualSpan = + match Seq.length visualSpan.PerLineSpans with + | 1 -> x.AddNextOccurrenceOfPrimarySelection count + | _ -> x.SplitSelectionIntoCarets visualSpan + /// Add the next occurrence of the primary selection member x.AddNextOccurrenceOfPrimarySelection count = let oldSelectedSpans = _commonOperations.SelectedSpans |> Seq.toList /// Whether the specified point is at a word boundary let isWordBoundary (point: SnapshotPoint) = let isStart = SnapshotPointUtil.IsStartPoint point let isEnd = SnapshotPointUtil.IsEndPoint point if isStart || isEnd then false else let pointChar = point |> SnapshotPointUtil.GetChar let previousPointChar = point |> SnapshotPointUtil.SubtractOne |> SnapshotPointUtil.GetChar let isWord = _wordUtil.IsKeywordChar pointChar let wasWord = _wordUtil.IsKeywordChar previousPointChar let isEmptyLine = SnapshotPointUtil.IsEmptyLine point isWord <> wasWord || isEmptyLine // Reset old selected spans and report failure to find a match. let reportNoMoreMatches () = _commonOperations.SetSelectedSpans oldSelectedSpans _statusUtil.OnError Resources.VisualMode_NoMoreMatches CommandResult.Error // Construct a regular expression pattern. let primarySelectedSpan = oldSelectedSpans |> Seq.head let span = primarySelectedSpan.Span.SnapshotSpan let pattern = seq { yield if isWordBoundary span.Start then @"\<" else "" yield @"\V" yield span.GetText().Replace(@"\", @"\\") yield @"\m" yield if isWordBoundary span.End then @"\>" else "" } |> String.concat "" // Create and store the search data. let path = SearchPath.Forward let searchKind = SearchKind.OfPathAndWrap path _globalSettings.WrapScan let options = SearchOptions.ConsiderIgnoreCase let searchData = SearchData(pattern, SearchOffsetData.None, searchKind, options) _vimData.LastSearchData <- searchData // Determine the search start and end points. let searchStartPoint, searchEndPoint = let primaryCaretPoint = primarySelectedSpan.Start.Position if oldSelectedSpans.Length = 1 then primaryCaretPoint, primaryCaretPoint else let sortedStartPoints = oldSelectedSpans |> Seq.map (fun selectedSpan -> selectedSpan.Start.Position) |> Seq.sortBy (fun point -> point.Position) |> Seq.toList let beforeStartPoints = sortedStartPoints |> Seq.filter (fun point -> point.Position < primaryCaretPoint.Position) |> Seq.toList let afterStartPoints = sortedStartPoints |> Seq.filter (fun point -> point.Position > primaryCaretPoint.Position) |> Seq.toList if beforeStartPoints.IsEmpty then afterStartPoints |> Seq.last, primaryCaretPoint else beforeStartPoints |> Seq.last, primaryCaretPoint // Whether the specified match point is in range. let isInRange (matchPoint: SnapshotPoint) = if searchStartPoint.Position < searchEndPoint.Position then matchPoint.Position > searchStartPoint.Position && matchPoint.Position < searchEndPoint.Position else matchPoint.Position > searchStartPoint.Position || matchPoint.Position < searchEndPoint.Position // Temporariliy move the caret to the search start point. TextViewUtil.MoveCaretToPointRaw _textView searchStartPoint MoveCaretFlags.None // Perform the search. let motion = Motion.LastSearch false let argument = MotionArgument(MotionContext.Movement, None, count) match _motionUtil.GetMotion motion argument with | Some motionResult -> // Found a match. let matchPoint = if motionResult.IsForward then motionResult.Span.End else motionResult.Span.Start if isInRange matchPoint then // Calculate the new selected span. let endPoint = SnapshotPointUtil.Add span.Length matchPoint let span = SnapshotSpan(matchPoint, endPoint) let isReversed = primarySelectedSpan.IsReversed let caretPoint = if isReversed then span.Start elif _globalSettings.IsSelectionInclusive && span.Length > 0 then span.End |> SnapshotPointUtil.GetPreviousCharacterSpanWithWrap else span.End let newSelectedSpan = SelectionSpan.FromSpan(caretPoint, span, isReversed) // Add the new selected span to the selection. seq { yield! oldSelectedSpans yield newSelectedSpan } |> _commonOperations.SetSelectedSpans CommandResult.Completed ModeSwitch.NoSwitch else reportNoMoreMatches() | None -> reportNoMoreMatches() /// Split the selection into carets member x.SplitSelectionIntoCarets visualSpan = let setCarets caretPoints = caretPoints |> Seq.map VirtualSnapshotPointUtil.OfPoint |> Seq.map SelectionSpan |> _commonOperations.SetSelectedSpans let splitLineRangeWith pointFunction = visualSpan.LineRange.Lines |> Seq.map pointFunction |> setCarets let getSpaceOnLine spaces line = let column = _commonOperations.GetColumnForSpacesOrEnd line spaces column.StartPoint + TextViewUtil.ClearSelection _textView + match visualSpan.VisualKind with | VisualKind.Character -> visualSpan.PerLineSpans |> Seq.map (fun span -> span.Start) |> setCarets () | VisualKind.Line -> SnapshotLineUtil.GetFirstNonBlankOrEnd |> splitLineRangeWith | VisualKind.Block -> _commonOperations.GetSpacesToPoint x.CaretPoint |> getSpaceOnLine |> splitLineRangeWith _commonOperations.EnsureAtCaret ViewFlags.Standard ModeSwitch.SwitchMode ModeKind.Normal |> CommandResult.Completed /// Restore the most recent set of multiple selections member x.RestoreMultiSelection () = if Seq.length _commonOperations.SelectedSpans = 1 then match _vimBufferData.LastMultiSelection with | Some (modeKind, selectedSpans) -> let restoredSelectedSpans = selectedSpans |> Seq.map _commonOperations.MapSelectedSpanToCurrentSnapshot |> Seq.toArray restoredSelectedSpans |> _commonOperations.SetSelectedSpans let allSelectionsAreEmpty = restoredSelectedSpans |> Seq.tryFind (fun span -> span.Length <> 0) |> Option.isNone if allSelectionsAreEmpty then CommandResult.Completed ModeSwitch.NoSwitch else ModeSwitch.SwitchMode modeKind |> CommandResult.Completed | None -> CommandResult.Error else CommandResult.Error /// Shift the given line range left by the specified value. The caret will be /// placed at the first character on the first line of the shifted text member x.ShiftLinesLeftCore range multiplier = // Use a transaction so the caret will be properly moved for undo / redo x.EditWithUndoTransaction "ShiftLeft" (fun () -> _commonOperations.ShiftLineRangeLeft range multiplier // Now move the caret to the first non-whitespace character on the first // line let line = SnapshotUtil.GetLine x.CurrentSnapshot range.StartLineNumber let point = match SnapshotLineUtil.GetFirstNonBlank line with | None -> SnapshotLineUtil.GetLastIncludedPoint line |> OptionUtil.getOrDefault line.Start | Some point -> point TextViewUtil.MoveCaretToPoint _textView point) /// Shift the given line range left by the specified value. The caret will be /// placed at the first character on the first line of the shifted text member x.ShiftLinesRightCore range multiplier = // Use a transaction so the caret will be properly moved for undo / redo x.EditWithUndoTransaction "ShiftRight" (fun () -> _commonOperations.ShiftLineRangeRight range multiplier // Now move the caret to the first non-whitespace character on the first // line let line = SnapshotUtil.GetLine x.CurrentSnapshot range.StartLineNumber let point = match SnapshotLineUtil.GetFirstNonBlank line with | None -> SnapshotLineUtil.GetLastIncludedPoint line |> OptionUtil.getOrDefault line.Start | Some point -> point TextViewUtil.MoveCaretToPoint _textView point) /// Shift 'count' lines to the left member x.ShiftLinesLeft count = let range = SnapshotLineRangeUtil.CreateForLineAndMaxCount x.CaretLine count x.ShiftLinesLeftCore range 1 CommandResult.Completed ModeSwitch.NoSwitch /// Shift 'motion' lines to the left by 'count' shiftwidth. member x.ShiftLinesLeftVisual count visualSpan = // Both Character and Line spans operate like most shifts match visualSpan with | VisualSpan.Character characterSpan -> let range = SnapshotLineRangeUtil.CreateForSpan characterSpan.Span x.ShiftLinesLeftCore range count | VisualSpan.Line range -> x.ShiftLinesLeftCore range count | VisualSpan.Block blockSpan -> // Shifting a block span is trickier because it doesn't shift at column // 0 but rather shifts at the start column of every span. It also treats // the caret much more different by keeping it at the start of the first // span vs. the start of the shift let targetCaretPosition = visualSpan.Start.Position // Use a transaction to preserve the caret. But move the caret first since // it needs to be undone to this location TextViewUtil.MoveCaretToPosition _textView targetCaretPosition x.EditWithUndoTransaction "ShiftLeft" (fun () -> _commonOperations.ShiftLineBlockLeft blockSpan.BlockSpans count TextViewUtil.MoveCaretToPosition _textView targetCaretPosition) CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Shift 'count' lines to the right member x.ShiftLinesRight count = let range = SnapshotLineRangeUtil.CreateForLineAndMaxCount x.CaretLine count x.ShiftLinesRightCore range 1 CommandResult.Completed ModeSwitch.NoSwitch /// Shift 'motion' lines to the right by 'count' shiftwidth member x.ShiftLinesRightVisual count visualSpan = // Both Character and Line spans operate like most shifts match visualSpan with | VisualSpan.Character characterSpan -> let range = SnapshotLineRangeUtil.CreateForSpan characterSpan.Span x.ShiftLinesRightCore range count | VisualSpan.Line range -> x.ShiftLinesRightCore range count | VisualSpan.Block blockSpan -> // Shifting a block span is trickier because it doesn't shift at column // 0 but rather shifts at the start column of every span. It also treats // the caret much more different by keeping it at the start of the first // span vs. the start of the shift let targetCaretPosition = visualSpan.Start.Position // Use a transaction to preserve the caret. But move the caret first since // it needs to be undone to this location TextViewUtil.MoveCaretToPosition _textView targetCaretPosition x.EditWithUndoTransaction "ShiftLeft" (fun () -> _commonOperations.ShiftLineBlockRight blockSpan.BlockSpans count TextViewUtil.MoveCaretToPosition _textView targetCaretPosition) CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Shift 'motion' lines to the left member x.ShiftMotionLinesLeft (result: MotionResult) = x.ShiftLinesLeftCore result.LineRange 1 CommandResult.Completed ModeSwitch.NoSwitch /// Shift 'motion' lines to the right member x.ShiftMotionLinesRight (result: MotionResult) = x.ShiftLinesRightCore result.LineRange 1 CommandResult.Completed ModeSwitch.NoSwitch /// Split the view horizontally member x.SplitViewHorizontally () = _vimHost.SplitViewHorizontally _textView CommandResult.Completed ModeSwitch.NoSwitch /// Split the view vertically member x.SplitViewVertically () = _vimHost.SplitViewVertically _textView CommandResult.Completed ModeSwitch.NoSwitch /// Substitute 'count' characters at the cursor on the current line. Very similar to /// DeleteCharacterAtCaret. Main exception is the behavior when the caret is on /// or after the last character in the line /// should be after the span for Substitute even if 've='. member x.SubstituteCharacterAtCaret count registerName = x.EditWithLinkedChange "Substitute" (fun () -> if x.CaretColumn.IsLineBreakOrEnd then // When we are past the end of the line just move the caret // to the end of the line and complete the command. Nothing should be deleted TextViewUtil.MoveCaretToPoint _textView x.CaretLine.End else let span = let endColumn = x.CaretColumn.AddInLineOrEnd count SnapshotColumnSpan(x.CaretColumn, endColumn) // Use a transaction so we can guarantee the caret is in the correct // position on undo / redo x.EditWithUndoTransaction "DeleteChar" (fun () -> _textBuffer.Delete(span.Span.Span) |> ignore span.Start.StartPoint.TranslateTo(_textBuffer.CurrentSnapshot, PointTrackingMode.Negative) |> TextViewUtil.MoveCaretToPoint _textView) // Put the deleted text into the specified register let value = RegisterValue(StringData.OfSpan span.Span, OperationKind.CharacterWise) _commonOperations.SetRegisterValue registerName RegisterOperation.Delete value) /// Subtract 'count' values from the word under the caret member x.SubtractFromWord count = x.AddToWord -count /// Subtract count from the word in each line of the selection, optionally progressively member x.SubtractFromSelection visualSpan count isProgressive = x.AddToSelection visualSpan -count isProgressive /// Switch to the given mode member x.SwitchMode modeKind modeArgument = CommandResult.Completed (ModeSwitch.SwitchModeWithArgument (modeKind, modeArgument)) /// Switch to the appropriate visual or select mode using the specified /// select mode options and visual selection member x.SwitchModeVisualOrSelect selectModeOptions visualSelection caretPoint = let modeKind = x.GetVisualOrSelectModeKind selectModeOptions visualSelection.VisualKind let modeArgument = ModeArgument.InitialVisualSelection (visualSelection, caretPoint) x.SwitchMode modeKind modeArgument /// Switch to the specified kind of visual mode member x.SwitchModeVisualCommand visualKind count = match count, _vimData.LastVisualSelection with | Some count, Some lastSelection -> let visualSelection = lastSelection.GetVisualSelection x.CaretPoint count let visualSelection = VisualSelection.CreateForward visualSelection.VisualSpan x.SwitchModeVisualOrSelect SelectModeOptions.Command visualSelection None | _ -> let modeKind = x.GetVisualOrSelectModeKind SelectModeOptions.Command visualKind CommandResult.Completed (ModeSwitch.SwitchMode modeKind) /// Get the appropriate visual or select mode kind for the specified /// select mode options and visual kind member x.GetVisualOrSelectModeKind selectModeOptions visualKind = if Util.IsFlagSet _globalSettings.SelectModeOptions selectModeOptions then visualKind.SelectModeKind else visualKind.VisualModeKind /// Switch to the previous Visual Span selection member x.SwitchPreviousVisualMode () = match _vimTextBuffer.LastVisualSelection with | None -> // If there is no available previous visual span then raise an error _statusUtil.OnError Resources.Common_NoPreviousVisualSpan CommandResult.Error | Some visualSelection -> let modeKind = visualSelection.VisualKind.VisualModeKind let modeArgument = ModeArgument.InitialVisualSelection (visualSelection, None) x.SwitchMode modeKind modeArgument /// Move the caret to the specified motion. How this command is implemented is largely dependent /// upon the values of 'keymodel' and 'selectmode'. It will either move the caret potentially as /// a motion or initiate a select in the editor member x.SwitchToSelection caretMovement = let anchorPoint = x.CaretVirtualPoint if not (_commonOperations.MoveCaretWithArrow caretMovement) then CommandResult.Error else let useVirtualSpace = _vimTextBuffer.UseVirtualSpace let visualSelection = VisualSelection.CreateForVirtualPoints VisualKind.Character anchorPoint x.CaretVirtualPoint _localSettings.TabStop useVirtualSpace let visualSelection = visualSelection.AdjustForSelectionKind _globalSettings.SelectionKind x.SwitchModeVisualOrSelect SelectModeOptions.Keyboard visualSelection None /// Switch from a visual mode to insert mode using the specified visual /// insert kind to determine the kind of insertion to perform member x.SwitchModeInsert (visualSpan: VisualSpan) (visualInsertKind: VisualInsertKind) = // Apply the 'end-of-line' setting in the visual span to the visual // insert kind. let visualInsertKind = match visualInsertKind, visualSpan with | VisualInsertKind.End, VisualSpan.Block blockSpan when blockSpan.EndOfLine -> VisualInsertKind.EndOfLine | _ -> visualInsertKind // Any undo should move the caret back to this position so make sure to // move it before we start the transaction so that it will be properly // positioned on undo. match visualInsertKind with | VisualInsertKind.Start -> visualSpan.Start | VisualInsertKind.End -> visualSpan.Spans |> Seq.head |> (fun span -> span.End) | VisualInsertKind.EndOfLine -> visualSpan.Start |> SnapshotPointUtil.GetContainingLine |> SnapshotLineUtil.GetEnd |> TextViewUtil.MoveCaretToPoint _textView match visualSpan with | VisualSpan.Block blockSpan -> x.EditBlockWithLinkedChange "Visual Insert" blockSpan visualInsertKind id | _ -> x.EditWithUndoTransaction "Visual Insert" id x.SwitchMode ModeKind.Insert ModeArgument.None /// Switch to the previous mode member x.SwitchPreviousMode() = CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Switch to other visual mode: visual from select or vice versa member x.SwitchModeOtherVisual visualSpan = let currentModeKind = _vimBufferData.VimTextBuffer.ModeKind match VisualKind.OfModeKind currentModeKind with | Some visualKind -> let newModeKind = if VisualKind.IsAnySelect currentModeKind then visualKind.VisualModeKind else visualKind.SelectModeKind x.SwitchMode newModeKind ModeArgument.None | None -> _commonOperations.Beep() CommandResult.Completed ModeSwitch.NoSwitch /// Switch from the current visual mode into the specified visual mode member x.SwitchModeVisual newVisualKind = let badOperation () = _commonOperations.Beep() CommandResult.Completed ModeSwitch.NoSwitch // The anchor point is the original anchor point of the visual session let anchorPoint = _vimBufferData.VisualAnchorPoint |> OptionUtil.map2 (TrackingPointUtil.GetPoint x.CurrentSnapshot) match anchorPoint with | None -> badOperation () | Some anchorPoint -> match _vimTextBuffer.ModeKind |> VisualKind.OfModeKind with | None -> badOperation () | Some currentVisualKind -> if currentVisualKind = newVisualKind then // Switching to the same mode just goes back to normal x.SwitchMode ModeKind.Normal ModeArgument.None else let caretPoint = x.CaretPoint let newVisualSelection = VisualSelection.CreateForPoints newVisualKind anchorPoint caretPoint _localSettings.TabStop let modeArgument = ModeArgument.InitialVisualSelection (newVisualSelection, Some anchorPoint) x.SwitchMode newVisualSelection.VisualKind.VisualModeKind modeArgument /// Undo count operations in the ITextBuffer member x.Undo count = use guard = new NormalModeSelectionGuard(_vimBufferData) _commonOperations.Undo count CommandResult.Completed ModeSwitch.NoSwitch /// Undo all recent changes made to the current line member x.UndoLine () = if not (_lineChangeTracker.Swap()) then _commonOperations.Beep() CommandResult.Completed ModeSwitch.NoSwitch /// Write out the ITextBuffer and quit member x.WriteBufferAndQuit () = let result = if _vimHost.IsDirty _textBuffer then _vimHost.Save _textBuffer else true if result then _vimHost.Close _textView CommandResult.Completed ModeSwitch.NoSwitch else CommandResult.Error /// Yank the specified lines into the specified register. This command should operate /// against the visual buffer if possible. Yanking a line which contains the fold should /// yank the entire fold member x.YankLines count registerName = let span = x.EditWithVisualSnapshot (fun x -> // Get the line range in the snapshot data let range = SnapshotLineRangeUtil.CreateForLineAndMaxCount x.CaretLine count range.ExtentIncludingLineBreak) match span with | None -> // If we couldn't map back down raise an error _statusUtil.OnError Resources.Internal_ErrorMappingToVisual | Some span -> let data = StringData.OfSpan span let value = x.CreateRegisterValue data OperationKind.LineWise _commonOperations.SetRegisterValue registerName RegisterOperation.Yank value _commonOperations.RecordLastYank span CommandResult.Completed ModeSwitch.NoSwitch /// Yank the contents of the motion into the specified register member x.YankMotion registerName (result: MotionResult) = let value = x.CreateRegisterValue (StringData.OfSpan result.Span) result.OperationKind _commonOperations.SetRegisterValue registerName RegisterOperation.Yank value match result.OperationKind with | OperationKind.CharacterWise -> TextViewUtil.MoveCaretToPoint _textView result.Start | _ -> () _commonOperations.RecordLastYank result.Span CommandResult.Completed ModeSwitch.NoSwitch /// Yank the lines in the specified selection member x.YankLineSelection registerName (visualSpan: VisualSpan) = let editSpan, operationKind = match visualSpan with | VisualSpan.Character characterSpan -> // Extend the character selection to the full lines let range = SnapshotLineRangeUtil.CreateForSpan characterSpan.Span EditSpan.Single range.ColumnExtentIncludingLineBreak, OperationKind.LineWise | VisualSpan.Line _ -> // Simple case, just use the visual span as is visualSpan.EditSpan, OperationKind.LineWise | VisualSpan.Block _ -> // Odd case. Don't treat any different than a normal yank visualSpan.EditSpan, visualSpan.OperationKind let data = StringData.OfEditSpan editSpan let value = x.CreateRegisterValue data operationKind _commonOperations.SetRegisterValue registerName RegisterOperation.Yank value _commonOperations.RecordLastYank editSpan.OverarchingSpan CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Yank the selection into the specified register member x.YankSelection registerName (visualSpan: VisualSpan) = let data = match visualSpan with | VisualSpan.Character characterSpan when characterSpan.UseVirtualSpace -> characterSpan.VirtualSpan |> VirtualSnapshotSpanUtil.GetText |> StringData.Simple | _ -> StringData.OfEditSpan visualSpan.EditSpan let value = x.CreateRegisterValue data visualSpan.OperationKind _commonOperations.SetRegisterValue registerName RegisterOperation.Yank value _commonOperations.RecordLastYank visualSpan.EditSpan.OverarchingSpan CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Cut selection member x.CutSelection () = _editorOperations.CutSelection() |> ignore CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Copy selection member x.CopySelection () = _editorOperations.CopySelection() |> ignore CommandResult.Completed ModeSwitch.NoSwitch /// Cut selection and paste member x.CutSelectionAndPaste () = _editorOperations.Paste() |> ignore CommandResult.Completed ModeSwitch.SwitchPreviousMode /// Select the whole document member x.SelectAll () = SnapshotUtil.GetExtent _textBuffer.CurrentSnapshot |> (fun span -> SelectionSpan.FromSpan(span.End, span, isReversed = false)) |> TextViewUtil.SelectSpan _textView CommandResult.Completed ModeSwitch.NoSwitch interface ICommandUtil with member x.RunNormalCommand command data = x.RunNormalCommand command data member x.RunVisualCommand command data visualSpan = x.RunVisualCommand command data visualSpan member x.RunInsertCommand command = x.RunInsertCommand command member x.RunCommand command = x.RunCommand command diff --git a/Src/VimCore/CoreInterfaces.fs b/Src/VimCore/CoreInterfaces.fs index 2764e1e..a7f3bdc 100644 --- a/Src/VimCore/CoreInterfaces.fs +++ b/Src/VimCore/CoreInterfaces.fs @@ -2877,1141 +2877,1139 @@ type PingData (_func: CommandData -> CommandResult) = member x.Equals other = x.Equals(other) /// Normal mode commands which can be executed by the user [<RequireQualifiedAccess>] [<NoComparison>] [<StructuralEquality>] type NormalCommand = /// Add a new caret at the mouse point | AddCaretAtMousePoint /// Add a new caret on an adjacent line in the specified direction | AddCaretOnAdjacentLine of Direction: Direction /// Add 'count' to the word close to the caret | AddToWord /// Cancel any in-progress operation such as external edit | CancelOperation /// Deletes the text specified by the motion and begins insert mode. Implements the "c" /// command | ChangeMotion of MotionData: MotionData /// Change the characters on the caret line | ChangeCaseCaretLine of ChangeCharacterKind: ChangeCharacterKind /// Change the characters on the caret line | ChangeCaseCaretPoint of ChangeCharacterKind: ChangeCharacterKind /// Change case of the specified motion | ChangeCaseMotion of ChangeCharacterKind: ChangeCharacterKind * MotionData: MotionData /// Delete 'count' lines and begin insert mode | ChangeLines /// Delete the text till the end of the line in the same manner as DeleteTillEndOfLine /// and start Insert Mode | ChangeTillEndOfLine /// Close all folds in the buffer | CloseAllFolds /// Close all folds under the caret | CloseAllFoldsUnderCaret /// Close the IVimBuffer and don't bother to save | CloseBuffer /// Close the window unless the buffer is dirty | CloseWindow /// Close 'count' folds under the caret | CloseFoldUnderCaret /// Delete all of the folds that are in the ITextBuffer | DeleteAllFoldsInBuffer /// Delete the character at the current cursor position. Implements the "x" command | DeleteCharacterAtCaret /// Delete the character before the cursor. Implements the "X" command | DeleteCharacterBeforeCaret /// Delete the fold under the caret | DeleteFoldUnderCaret /// Delete all folds under the caret | DeleteAllFoldsUnderCaret /// Delete lines from the buffer: dd | DeleteLines /// Delete the specified motion of text | DeleteMotion of MotionData: MotionData /// Delete till the end of the line and 'count - 1' more lines down | DeleteTillEndOfLine /// Display the bytes of the current character in the status bar | DisplayCharacterBytes /// Display the ascii (or really code point) value of the current character | DisplayCharacterCodePoint /// Fold 'count' lines in the ITextBuffer | FoldLines /// Filter the specified lines | FilterLines /// Filter the specified motion | FilterMotion of MotionData: MotionData /// Create a fold over the specified motion | FoldMotion of MotionData: MotionData /// Format the code in the specified lines | FormatCodeLines /// Format the code in the specified motion | FormatCodeMotion of MotionData: MotionData /// Format the text in the specified lines, optionally preserving the caret position | FormatTextLines of PreserveCaretPosition: bool /// Format the text in the specified motion | FormatTextMotion of PreserveCaretPosition: bool * MotionData: MotionData /// Go to the definition of the word under the caret | GoToDefinition /// Go to the definition of the word under the mouse | GoToDefinitionUnderMouse /// GoTo the file under the cursor. The bool represents whether or not this should occur in /// a different window | GoToFileUnderCaret of UseNewWindow: bool /// Go to the global declaration of the word under the caret | GoToGlobalDeclaration /// Go to the local declaration of the word under the caret | GoToLocalDeclaration /// Go to the next tab in the specified direction | GoToNextTab of SearchPath: SearchPath /// Go to the window of the specified kind | GoToWindow of WindowKind: WindowKind /// Go to the nth most recent view | GoToRecentView /// Switch to insert after the caret position | InsertAfterCaret /// Switch to insert mode | InsertBeforeCaret /// Switch to insert mode at the end of the line | InsertAtEndOfLine /// Insert text at the first non-blank line in the current line | InsertAtFirstNonBlank /// Insert text at the start of a line (column 0) | InsertAtStartOfLine /// Insert a line above the cursor and begin insert mode | InsertLineAbove /// Insert a line below the cursor and begin insert mode | InsertLineBelow /// Join the specified lines | JoinLines of JoinKind: JoinKind /// Jump to the specified mark | JumpToMark of Mark: Mark /// Jump to the start of the line for the specified mark | JumpToMarkLine of Mark: Mark /// Jump to the next older item in the tag list | JumpToOlderPosition /// Jump to the next new item in the tag list | JumpToNewerPosition /// Move the caret to the result of the given Motion. | MoveCaretToMotion of Motion: Motion /// Move the caret to position of the mouse cursor | MoveCaretToMouse /// Perform no operation | NoOperation /// Undo count operations in the ITextBuffer | Undo /// Undo all recent changes made to the current line | UndoLine /// Open all folds in the buffer | OpenAllFolds /// Open all of the folds under the caret | OpenAllFoldsUnderCaret /// Open link under caret | OpenLinkUnderCaret /// Open a fold under the caret | OpenFoldUnderCaret /// Toggle a fold under the caret | ToggleFoldUnderCaret /// Toggle all folds under the caret | ToggleAllFolds /// Not actually a Vim Command. This is a simple ping command which makes /// testing items like complex repeats significantly easier | Ping of PingData: PingData /// Put the contents of the register into the buffer after the cursor. The bool is /// whether or not the caret should be placed after the inserted text | PutAfterCaret of PlaceCaretAfterInsertedText: bool /// Put the contents of the register into the buffer after the cursor and respecting /// the indent of the current line | PutAfterCaretWithIndent /// Put the contents of the register after the current mouse position. This will move /// the mouse to that position before inserting | PutAfterCaretMouse /// Put the contents of the register into the buffer before the cursor. The bool is /// whether or not the caret should be placed after the inserted text | PutBeforeCaret of PlaceCaretAfterInsertedText: bool /// Put the contents of the register into the buffer before the cursor and respecting /// the indent of the current line | PutBeforeCaretWithIndent /// Print out the current file information | PrintFileInformation /// Start the recording of a macro to the specified Register | RecordMacroStart of RegisterName: char /// Stop the recording of a macro to the specified Register | RecordMacroStop /// Redo count operations in the ITextBuffer | Redo /// Repeat the last command | RepeatLastCommand /// Repeat the last substitute command. The first bool value is for /// whether or not the flags from the last substitute should be reused as /// well. The second bool value is for whether the substitute should /// operate on the whole buffer | RepeatLastSubstitute of UseSameFlags: bool * UseWholeBuffer: bool /// Replace the text starting at the text by starting insert mode | ReplaceAtCaret /// Replace the char under the cursor with the given char | ReplaceChar of KeyInput: KeyInput /// Restore the most recent set of multiple selections | RestoreMultiSelection /// Run an 'at' command for the specified character | RunAtCommand of Character: char /// Set the specified mark to the current value of the caret | SetMarkToCaret of Character: char /// Scroll the caret in the specified direciton. The bool is whether to use /// the 'scroll' option or 'count' | ScrollLines of ScrollDirection: ScrollDirection * UseScrollOption: bool /// Move the display a single page in the specified direction | ScrollPages of ScrollDirection: ScrollDirection /// Scroll the window in the specified direction by 'count' lines | ScrollWindow of ScrollDirection: ScrollDirection /// Scroll the current line to the top of the ITextView. The bool is whether or not /// to leave the caret in the same column | ScrollCaretLineToTop of MaintainCaretColumn: bool /// Scroll the caret line to the middle of the ITextView. The bool is whether or not /// to leave the caret in the same column | ScrollCaretLineToMiddle of MaintainCaretColumn: bool /// Scroll the caret line to the bottom of the ITextView. The bool is whether or not /// to leave the caret in the same column | ScrollCaretLineToBottom of MaintainCaretColumn: bool /// Scroll the window horizontally so that the caret is at the left edge /// of the screen | ScrollCaretColumnToLeft /// Scroll the window horizontally so that the caret is at the right edge /// of the screen | ScrollCaretColumnToRight /// Scroll the window horizontally in the specified direction | ScrollColumns of Direction: Direction /// Scroll half the width of the window in the specified direction | ScrollHalfWidth of Direction: Direction /// Select the current block | SelectBlock /// Select the current line | SelectLine /// Select the next match for the last pattern searched for | SelectNextMatch of SearchPath: SearchPath /// Select text for a mouse click | SelectTextForMouseClick /// Select text for a mouse drag | SelectTextForMouseDrag /// Select text for a mouse release | SelectTextForMouseRelease /// Select the word or matching token under the caret | SelectWordOrMatchingToken /// Select the word or matching token at the mouse point | SelectWordOrMatchingTokenAtMousePoint /// Shift 'count' lines from the cursor left | ShiftLinesLeft /// Shift 'count' lines from the cursor right | ShiftLinesRight /// Shift 'motion' lines from the cursor left | ShiftMotionLinesLeft of MotionData: MotionData /// Shift 'motion' lines from the cursor right | ShiftMotionLinesRight of MotionData: MotionData /// Split the view horizontally | SplitViewHorizontally /// Split the view vertically | SplitViewVertically /// Substitute the character at the cursor | SubstituteCharacterAtCaret /// Subtract 'count' from the word at the caret | SubtractFromWord /// Switch modes with the specified information | SwitchMode of ModeKind: ModeKind * ModeArgument: ModeArgument /// Switch to the specified kind of visual mode | SwitchModeVisualCommand of VisualKind: VisualKind /// Switch to the previous Visual Mode selection | SwitchPreviousVisualMode /// Switch to a selection dictated by the given caret movement | SwitchToSelection of CaretMovement: CaretMovement /// Write out the ITextBuffer and quit | WriteBufferAndQuit /// Yank the given motion into a register | Yank of MotionData: MotionData /// Yank the specified number of lines | YankLines with member x.MotionData = match x.GetMotionDataCore() with | Some (_, motionData) -> Some motionData | None -> None member private x.GetMotionDataCore() = match x with | NormalCommand.ChangeCaseMotion (changeCharacterKind, motion) -> Some ((fun motion -> NormalCommand.ChangeCaseMotion (changeCharacterKind, motion)), motion) | NormalCommand.ChangeMotion motion -> Some (NormalCommand.ChangeMotion, motion) | NormalCommand.DeleteMotion motion -> Some (NormalCommand.DeleteMotion, motion) | NormalCommand.FilterMotion motion -> Some (NormalCommand.FilterMotion, motion) | NormalCommand.FoldMotion motion -> Some (NormalCommand.FoldMotion, motion) | NormalCommand.FormatCodeMotion motion -> Some (NormalCommand.FormatCodeMotion, motion) | NormalCommand.FormatTextMotion (preserveCaretPosition, motion) -> Some ((fun motion -> NormalCommand.FormatTextMotion (preserveCaretPosition, motion)), motion) | NormalCommand.ShiftMotionLinesLeft motion -> Some (NormalCommand.ShiftMotionLinesLeft, motion) | NormalCommand.ShiftMotionLinesRight motion -> Some (NormalCommand.ShiftMotionLinesRight, motion) | NormalCommand.Yank motion -> Some (NormalCommand.Yank, motion) // Non-motion commands | NormalCommand.AddCaretAtMousePoint -> None | NormalCommand.AddCaretOnAdjacentLine _ -> None | NormalCommand.AddToWord _ -> None | NormalCommand.CancelOperation -> None | NormalCommand.ChangeCaseCaretLine _ -> None | NormalCommand.ChangeCaseCaretPoint _ -> None | NormalCommand.ChangeLines -> None | NormalCommand.ChangeTillEndOfLine -> None | NormalCommand.CloseAllFolds -> None | NormalCommand.CloseAllFoldsUnderCaret -> None | NormalCommand.CloseBuffer -> None | NormalCommand.CloseWindow -> None | NormalCommand.CloseFoldUnderCaret -> None | NormalCommand.DeleteAllFoldsInBuffer -> None | NormalCommand.DeleteCharacterAtCaret -> None | NormalCommand.DeleteCharacterBeforeCaret -> None | NormalCommand.DeleteFoldUnderCaret -> None | NormalCommand.DeleteAllFoldsUnderCaret -> None | NormalCommand.DeleteLines -> None | NormalCommand.DeleteTillEndOfLine -> None | NormalCommand.DisplayCharacterBytes -> None | NormalCommand.DisplayCharacterCodePoint ->None | NormalCommand.FilterLines -> None | NormalCommand.FoldLines -> None | NormalCommand.FormatCodeLines -> None | NormalCommand.FormatTextLines _ -> None | NormalCommand.GoToDefinition -> None | NormalCommand.GoToDefinitionUnderMouse -> None | NormalCommand.GoToFileUnderCaret _ -> None | NormalCommand.GoToGlobalDeclaration -> None | NormalCommand.GoToLocalDeclaration -> None | NormalCommand.GoToNextTab _ -> None | NormalCommand.GoToWindow _ -> None | NormalCommand.GoToRecentView _ -> None | NormalCommand.InsertAfterCaret -> None | NormalCommand.InsertBeforeCaret -> None | NormalCommand.InsertAtEndOfLine -> None | NormalCommand.InsertAtFirstNonBlank -> None | NormalCommand.InsertAtStartOfLine -> None | NormalCommand.InsertLineAbove -> None | NormalCommand.InsertLineBelow -> None | NormalCommand.JoinLines _ -> None | NormalCommand.JumpToMark _ -> None | NormalCommand.JumpToMarkLine _ -> None | NormalCommand.JumpToOlderPosition -> None | NormalCommand.JumpToNewerPosition -> None | NormalCommand.MoveCaretToMotion _ -> None | NormalCommand.MoveCaretToMouse -> None | NormalCommand.NoOperation -> None | NormalCommand.Undo -> None | NormalCommand.UndoLine -> None | NormalCommand.OpenAllFolds -> None | NormalCommand.OpenAllFoldsUnderCaret -> None | NormalCommand.OpenLinkUnderCaret -> None | NormalCommand.OpenFoldUnderCaret -> None | NormalCommand.ToggleFoldUnderCaret -> None | NormalCommand.ToggleAllFolds -> None | NormalCommand.Ping _ -> None | NormalCommand.PutAfterCaret _ -> None | NormalCommand.PutAfterCaretWithIndent -> None | NormalCommand.PutAfterCaretMouse -> None | NormalCommand.PutBeforeCaret _ -> None | NormalCommand.PutBeforeCaretWithIndent -> None | NormalCommand.PrintFileInformation -> None | NormalCommand.RecordMacroStart _ -> None | NormalCommand.RecordMacroStop -> None | NormalCommand.Redo -> None | NormalCommand.RepeatLastCommand -> None | NormalCommand.RepeatLastSubstitute _ -> None | NormalCommand.ReplaceAtCaret -> None | NormalCommand.ReplaceChar _ -> None | NormalCommand.RestoreMultiSelection -> None | NormalCommand.RunAtCommand _ -> None | NormalCommand.SetMarkToCaret _ -> None | NormalCommand.ScrollColumns _ -> None | NormalCommand.ScrollHalfWidth _ -> None | NormalCommand.ScrollLines _ -> None | NormalCommand.ScrollPages _ -> None | NormalCommand.ScrollWindow _ -> None | NormalCommand.ScrollCaretLineToTop _ -> None | NormalCommand.ScrollCaretLineToMiddle _ -> None | NormalCommand.ScrollCaretLineToBottom _ -> None | NormalCommand.ScrollCaretColumnToLeft -> None | NormalCommand.ScrollCaretColumnToRight -> None | NormalCommand.SelectBlock -> None | NormalCommand.SelectLine -> None | NormalCommand.SelectNextMatch _ -> None | NormalCommand.SelectTextForMouseClick -> None | NormalCommand.SelectTextForMouseDrag -> None | NormalCommand.SelectTextForMouseRelease -> None | NormalCommand.SelectWordOrMatchingToken -> None | NormalCommand.SelectWordOrMatchingTokenAtMousePoint -> None | NormalCommand.ShiftLinesLeft -> None | NormalCommand.ShiftLinesRight -> None | NormalCommand.SplitViewHorizontally -> None | NormalCommand.SplitViewVertically -> None | NormalCommand.SubstituteCharacterAtCaret -> None | NormalCommand.SubtractFromWord -> None | NormalCommand.SwitchMode _ -> None | NormalCommand.SwitchModeVisualCommand _ -> None | NormalCommand.SwitchPreviousVisualMode -> None | NormalCommand.SwitchToSelection _ -> None | NormalCommand.WriteBufferAndQuit -> None | NormalCommand.YankLines -> None /// Change the MotionData associated with this command if it's a part of the command. Otherwise it /// returns the original command unchanged member x.ChangeMotionData changeMotionFunc = match x.GetMotionDataCore() with | Some (createCommandFunc, motionData) -> let motionData = changeMotionFunc motionData createCommandFunc motionData | None -> x /// Visual mode commands which can be executed by the user [<RequireQualifiedAccess>] [<NoComparison>] [<StructuralEquality>] type VisualCommand = /// Add a new caret at the mouse point | AddCaretAtMousePoint - /// Add the next occurrence of the primary selection - | AddNextOccurrenceOfPrimarySelection - /// Add a new selection on an adjacent line in the specified direction | AddSelectionOnAdjacentLine of Direction: Direction /// Add count to the word in each line of the selection, optionally progressively | AddToSelection of IsProgressive: bool /// Add word or matching token at the current mouse point to the selection | AddWordOrMatchingTokenAtMousePointToSelection /// Cancel any in-progress operation | CancelOperation /// Change the case of the selected text in the specified manner | ChangeCase of ChangeCharacterKind: ChangeCharacterKind /// Delete the selection and begin insert mode. Implements the 'c' and 's' commands | ChangeSelection /// Delete the selected lines and begin insert mode ('S' and 'C' commands). The bool parameter /// is whether or not to treat block selection as a special case | ChangeLineSelection of SpecialCaseBlockSelection: bool /// Close a fold in the selection | CloseFoldInSelection /// Close all folds in the selection | CloseAllFoldsInSelection /// Delete all folds in the selection | DeleteAllFoldsInSelection /// Delete the selected lines | DeleteLineSelection /// Delete the selected text and put it into a register | DeleteSelection /// Extend the selection for a mouse click | ExtendSelectionForMouseClick /// Extend the selection for a mouse drag | ExtendSelectionForMouseDrag /// Extend the selection for a mouse release | ExtendSelectionForMouseRelease /// Extend the selection to the next match for the last pattern searched for | ExtendSelectionToNextMatch of SearchPath: SearchPath /// Filter the selected text | FilterLines /// Fold the current selected lines | FoldSelection /// Format the selected code lines | FormatCodeLines /// Format the selected text lines, optionally preserving the caret position | FormatTextLines of PreserveCaretPosition: bool /// GoTo the file under the cursor in a new window | GoToFileInSelectionInNewWindow /// GoTo the file under the cursor in this window | GoToFileInSelection /// Join the selected lines | JoinSelection of JoinKind: JoinKind /// Invert the selection by swapping the caret and anchor points. When true it means that block mode should /// be special cased to invert the column only | InvertSelection of ColumnOnlyInBlock: bool /// Move the caret to the mouse position | MoveCaretToMouse /// Move the caret to the result of the given Motion. This movement is from a /// text-object selection. Certain motions | MoveCaretToTextObject of Motion: Motion * TextObjectKind: TextObjectKind /// Open all folds in the selection | OpenAllFoldsInSelection /// Open link in selection | OpenLinkInSelection /// Open one fold in the selection | OpenFoldInSelection /// Put the contents af the register after the selection. The bool is for whether or not the // caret should be placed after the inserted text | PutOverSelection of PlaceCaretAfterInsertedText: bool /// Replace the visual span with the provided character | ReplaceSelection of KeyInput: KeyInput /// Select current block | SelectBlock /// Select current line | SelectLine /// Select current word or matching token | SelectWordOrMatchingTokenAtMousePoint /// Shift the selected lines left | ShiftLinesLeft /// Shift the selected lines to the right | ShiftLinesRight - /// Shift the selection into carets - | SplitSelectionIntoCarets + /// Add the next occurrence of the primary selection or split the + /// selection into carets + | StartMultiSelection /// Subtract count from the word in each line of the selection, optionally progressively | SubtractFromSelection of IsProgressive: bool /// Switch from a visual mode to insert mode using the specified visual /// insert kind to determine the kind of insertion to perform | SwitchModeInsert of VisualInsertKind: VisualInsertKind /// Switch to the previous mode | SwitchModePrevious /// Switch to the specified visual mode | SwitchModeVisual of VisualKind: VisualKind /// Toggle one fold in the selection | ToggleFoldInSelection /// Toggle all folds in the selection | ToggleAllFoldsInSelection /// Yank the lines which are specified by the selection | YankLineSelection /// Yank the selection into the specified register | YankSelection /// Switch to the other visual mode, visual or select | SwitchModeOtherVisual /// Cut selection | CutSelection /// Copy selection | CopySelection /// Cut selection and paste | CutSelectionAndPaste /// Select the whole document | SelectAll /// Insert mode commands that can be executed by the user [<RequireQualifiedAccess>] [<NoComparison>] [<StructuralEquality>] type InsertCommand = /// Backspace at the current caret position | Back /// Block edit of the specified TextChange value. The first bool /// specifies whether short lines should be padded. The second bool /// specifieds whether the insert is at the end of the line. The int /// represents the number of lines on which this block insert should take /// place | BlockInsert of InsertCommand: InsertCommand * PadShortLines: bool * AtEndOfLine: bool * Height: int /// This is an insert command which is a combination of other insert commands | Combined of Left: InsertCommand * Right: InsertCommand /// Complete the Insert Mode session. This is done as a command so that it will /// be a bookend of insert mode for the repeat infrastructure /// /// The bool value represents whether or not the caret needs to be moved to the /// left | CompleteMode of MoveCaretLeft: bool /// Delete the character under the caret | Delete /// Delete count characters to the left of the caret | DeleteLeft of ColumnCount: int /// Delete count characters to the right of the caret | DeleteRight of ColumnCount: int /// Delete all indentation on the current line | DeleteAllIndent /// Delete the word before the cursor | DeleteWordBeforeCursor /// Insert the character which is immediately above the caret | InsertCharacterAboveCaret /// Insert the character which is immediately below the caret | InsertCharacterBelowCaret /// Insert a new line into the ITextBuffer | InsertNewLine /// Insert previously inserted text, optionally stopping insert | InsertPreviouslyInsertedText of StopInsert: bool /// Insert a tab into the ITextBuffer | InsertTab /// Insert of text into the ITextBuffer at the caret position | Insert of Text: string /// Insert of literal text into the ITextBuffer at the caret position | InsertLiteral of Text: string /// Move the caret in the given direction | MoveCaret of Direction: Direction /// Move the caret in the given direction with an arrow key | MoveCaretWithArrow of Direction: Direction /// Move the caret in the given direction by a whole word | MoveCaretByWord of Direction: Direction /// Move the caret to the end of the line | MoveCaretToEndOfLine /// Replace the character under the caret with the specified value | Replace of Character: char /// Replace the character which is immediately above the caret | ReplaceCharacterAboveCaret /// Replace the character which is immediately below the caret | ReplaceCharacterBelowCaret /// Overwrite the characters under the caret with the specified string | Overwrite of Text: string /// Shift the current line one indent width to the left | ShiftLineLeft /// Shift the current line one indent width to the right | ShiftLineRight /// Undo replace | UndoReplace /// Delete non-blank characters before cursor on current line | DeleteLineBeforeCursor /// Paste clipboard | Paste with member x.RightMostCommand = match x with | InsertCommand.Combined (_, right) -> right.RightMostCommand | _ -> x member x.SecondRightMostCommand = match x with | InsertCommand.Combined (left, right) -> match right with | InsertCommand.Combined (_, right) -> right.SecondRightMostCommand | _ -> Some left | _ -> None /// Convert a TextChange value into the appropriate InsertCommand structure static member OfTextChange textChange = match textChange with | TextChange.Insert text -> InsertCommand.Insert text | TextChange.DeleteLeft count -> InsertCommand.DeleteLeft count | TextChange.DeleteRight count -> InsertCommand.DeleteRight count | TextChange.Combination (left, right) -> let leftCommand = InsertCommand.OfTextChange left let rightCommand = InsertCommand.OfTextChange right InsertCommand.Combined (leftCommand, rightCommand) /// Convert this InsertCommand to a TextChange object member x.TextChange editorOptions textBuffer = match x with | InsertCommand.Back -> Some (TextChange.DeleteLeft 1) | InsertCommand.BlockInsert _ -> None | InsertCommand.Combined (left, right) -> match left.TextChange editorOptions textBuffer, right.TextChange editorOptions textBuffer with | Some l, Some r -> TextChange.Combination (l, r) |> Some | _ -> None | InsertCommand.CompleteMode _ -> None | InsertCommand.Delete -> Some (TextChange.DeleteRight 1) | InsertCommand.DeleteLeft count -> Some (TextChange.DeleteLeft count) | InsertCommand.DeleteRight count -> Some (TextChange.DeleteRight count) | InsertCommand.DeleteAllIndent -> None | InsertCommand.DeleteWordBeforeCursor -> None | InsertCommand.Insert text -> Some (TextChange.Insert text) | InsertCommand.InsertLiteral text -> Some (TextChange.Insert text) | InsertCommand.InsertCharacterAboveCaret -> None | InsertCommand.InsertCharacterBelowCaret -> None | InsertCommand.InsertNewLine -> Some (TextChange.Insert (EditUtil.NewLine editorOptions textBuffer)) | InsertCommand.InsertPreviouslyInsertedText _ -> None | InsertCommand.InsertTab -> Some (TextChange.Insert "\t") | InsertCommand.MoveCaret _ -> None | InsertCommand.MoveCaretWithArrow _ -> None | InsertCommand.MoveCaretByWord _ -> None | InsertCommand.MoveCaretToEndOfLine -> None | InsertCommand.Replace c -> Some (TextChange.Combination ((TextChange.DeleteRight 1), (TextChange.Insert (c.ToString())))) | InsertCommand.ReplaceCharacterAboveCaret -> None | InsertCommand.ReplaceCharacterBelowCaret -> None | InsertCommand.Overwrite s -> Some (TextChange.Replace s) | InsertCommand.ShiftLineLeft -> None | InsertCommand.ShiftLineRight -> None | InsertCommand.UndoReplace -> None | InsertCommand.DeleteLineBeforeCursor -> None | InsertCommand.Paste -> None /// Commands which can be executed by the user [<RequireQualifiedAccess>] [<StructuralEquality>] [<NoComparison>] type Command = /// A Normal Mode Command | NormalCommand of NormalCommand: NormalCommand * CommandData: CommandData /// A Visual Mode Command | VisualCommand of VisualCommand: VisualCommand * CommandData: CommandData * VisualSpan: VisualSpan /// An Insert / Replace Mode Command | InsertCommand of InsertCommand: InsertCommand /// This is the result of attemping to bind a series of KeyInput values into a Motion /// Command, etc ... [<RequireQualifiedAccess>] type BindResult<'T> = /// Successfully bound to a value | Complete of Result: 'T /// More input is needed to complete the binding operation | NeedMoreInput of BindData: BindData<'T> /// There was an error completing the binding operation | Error /// Motion was cancelled via user input | Cancelled with /// Used to compose to BindResult<'T> functions together by forwarding from /// one to the other once the value is completed member x.Map (mapFunc: 'T -> BindResult<'U>): BindResult<'U> = match x with | Complete value -> mapFunc value | NeedMoreInput (bindData: BindData<'T>) -> NeedMoreInput (bindData.Map mapFunc) | Error -> Error | Cancelled -> Cancelled /// Used to convert a BindResult<'T>.Completed to BindResult<'U>.Completed through a conversion /// function member x.Convert (convertFunc: 'T -> 'U): BindResult<'U> = x.Map (fun value -> convertFunc value |> BindResult.Complete) and BindData<'T> = { /// The optional KeyRemapMode which should be used when binding /// the next KeyInput in the sequence KeyRemapMode: KeyRemapMode /// Function to call to get the BindResult for this data BindFunction: KeyInput -> BindResult<'T> } with member x.CreateBindResult() = BindResult.NeedMoreInput x /// Used for BindData where there can only be a complete result for a given /// KeyInput. static member CreateForKeyInput keyRemapMode valueFunc = let bindFunc keyInput = let value = valueFunc keyInput BindResult<_>.Complete value { KeyRemapMode = keyRemapMode; BindFunction = bindFunc } /// Used for BindData where there can only be a complete result for a given /// char static member CreateForChar keyRemapMode valueFunc = BindData<_>.CreateForKeyInput keyRemapMode (fun keyInput -> valueFunc keyInput.Char) /// Very similar to the Convert function. This will instead map a BindData<'T>.Completed /// to a BindData<'U> of any form member x.Map<'U> (mapFunc: 'T -> BindResult<'U>): BindData<'U> = let originalBindFunc = x.BindFunction let bindFunc keyInput = match originalBindFunc keyInput with | BindResult.Cancelled -> BindResult.Cancelled | BindResult.Complete value -> mapFunc value | BindResult.Error -> BindResult.Error | BindResult.NeedMoreInput bindData -> BindResult.NeedMoreInput (bindData.Map mapFunc) { KeyRemapMode = x.KeyRemapMode; BindFunction = bindFunc } /// Often types bindings need to compose together because we need an inner binding /// to succeed so we can create a projected value. This function will allow us /// to translate a BindResult<'T>.Completed -> BindResult<'U>.Completed member x.Convert (convertFunc: 'T -> 'U): BindData<'U> = x.Map (fun value -> convertFunc value |> BindResult.Complete) /// Several types of BindData<'T> need to take an action when a binding begins against /// themselves. This action needs to occur before the first KeyInput value is processed /// and hence they need a jump start. The most notable is IncrementalSearch which /// needs to enter 'Search' mode before processing KeyInput values so the cursor can /// be updated [<RequireQualifiedAccess>] type BindDataStorage<'T> = /// Simple BindData<'T> which doesn't require activation | Simple of BindData: BindData<'T> /// Complex BindData<'T> which does require activation | Complex of CreateBindDataFunc: (unit -> BindData<'T>) with /// Creates the BindData member x.CreateBindData () = match x with | Simple bindData -> bindData | Complex func -> func() /// Convert from a BindDataStorage<'T> -> BindDataStorage<'U>. The 'mapFunc' value /// will run on the final 'T' data if it eventually is completed member x.Convert mapFunc = match x with | Simple bindData -> Simple (bindData.Convert mapFunc) | Complex func -> Complex (fun () -> func().Convert mapFunc) /// This is the result of attemping to bind a series of KeyInputData values /// into a Motion Command, etc ... [<RequireQualifiedAccess>] type MappedBindResult<'T> = /// Successfully bound to a value | Complete of Result: 'T /// More input is needed to complete the binding operation | NeedMoreInput of MappedBindData: MappedBindData<'T> /// There was an error completing the binding operation | Error /// Motion was cancelled via user input | Cancelled with /// Used to compose to MappedBindResult<'T> functions together by /// forwarding from one to the other once the value is completed member x.Map (mapFunc: 'T -> MappedBindResult<'U>): MappedBindResult<'U> = match x with | Complete value -> mapFunc value | NeedMoreInput (bindData: MappedBindData<'T>) -> NeedMoreInput (bindData.Map mapFunc) | Error -> Error | Cancelled -> Cancelled /// Used to convert a MappedBindResult<'T>.Completed to /// MappedBindResult<'U>.Completed through a conversion function member x.Convert (convertFunc: 'T -> 'U): MappedBindResult<'U> = x.Map (fun value -> convertFunc value |> MappedBindResult.Complete) /// Convert this MappedBindResult<'T> to a BindResult<'T> member x.ConvertToBindResult (): BindResult<'T> = match x with | MappedBindResult.Complete result -> BindResult.Complete result | MappedBindResult.NeedMoreInput mappedBindData -> BindResult.NeedMoreInput (mappedBindData.ConvertToBindData()) | MappedBindResult.Error -> BindResult.Error | MappedBindResult.Cancelled -> BindResult.Cancelled and MappedBindData<'T> = { /// The optional KeyRemapMode which should be used when binding the next /// KeyInput in the sequence KeyRemapMode: KeyRemapMode /// Function to call to get the MappedBindResult for this data MappedBindFunction: KeyInputData -> MappedBindResult<'T> } with member x.CreateBindResult() = MappedBindResult.NeedMoreInput x /// Very similar to the Convert function. This will instead map a /// MappedBindData<'T>.Completed to a MappedBindData<'U> of any form member x.Map<'U> (mapFunc: 'T -> MappedBindResult<'U>): MappedBindData<'U> = let originalBindFunc = x.MappedBindFunction let bindFunc keyInputData = match originalBindFunc keyInputData with | MappedBindResult.Complete value -> mapFunc value | MappedBindResult.NeedMoreInput mappedBindData -> MappedBindResult.NeedMoreInput (mappedBindData.Map mapFunc) | MappedBindResult.Error -> MappedBindResult.Error | MappedBindResult.Cancelled -> MappedBindResult.Cancelled { KeyRemapMode = x.KeyRemapMode; MappedBindFunction = bindFunc } /// Often types bindings need to compose together because we need an inner /// binding to succeed so we can create a projected value. This function /// will allow us to translate a MappedBindResult<'T>.Completed -> /// MappedBindResult<'U>.Completed member x.Convert (convertFunc: 'T -> 'U): MappedBindData<'U> = x.Map (fun value -> convertFunc value |> MappedBindResult.Complete) /// Convert this MappedBindData<'T> to a BindData<'T> (note that as a /// result of the conversion all key inputs will all appear to be unmapped) member x.ConvertToBindData (): BindData<'T> = let bindFunc keyInput = KeyInputData.Create keyInput false |> x.MappedBindFunction |> (fun mappedBindResult -> mappedBindResult.ConvertToBindResult()) { KeyRemapMode = x.KeyRemapMode; BindFunction = bindFunc } /// Several types of MappedBindData<'T> need to take an action when a binding /// begins against themselves. This action needs to occur before the first /// KeyInput value is processed and hence they need a jump start. The most /// notable is IncrementalSearch which needs to enter 'Search' mode before /// processing KeyInput values so the cursor can be updated [<RequireQualifiedAccess>] type MappedBindDataStorage<'T> = /// Simple MappedBindData<'T> which doesn't require activation | Simple of MappedBindData: MappedBindData<'T> /// Complex MappedBindData<'T> which does require activation | Complex of CreateBindDataFunc: (unit -> MappedBindData<'T>) with /// Creates the MappedBindData member x.CreateMappedBindData () = match x with | Simple bindData -> bindData | Complex func -> func() /// Convert from a MappedBindDataStorage<'T> -> MappedBindDataStorage<'U>. /// The 'mapFunc' value will run on the final 'T' data if it eventually is /// completed member x.Convert mapFunc = match x with | Simple bindData -> Simple (bindData.Convert mapFunc) | Complex func -> Complex (fun () -> func().Convert mapFunc) /// Representation of binding of Command's to KeyInputSet values and flags which correspond /// to the execution of the command [<DebuggerDisplay("{ToString(),nq}")>] [<RequireQualifiedAccess>] type CommandBinding = /// KeyInputSet bound to a particular NormalCommand instance | NormalBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * NormalCommand: NormalCommand /// KeyInputSet bound to a complex NormalCommand instance | ComplexNormalBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * BindDataStorage: BindDataStorage<NormalCommand> /// KeyInputSet bound to a particular NormalCommand instance which takes a Motion Argument | MotionBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * Func: (MotionData -> NormalCommand) /// KeyInputSet bound to a particular VisualCommand instance | VisualBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * VisualCommand: VisualCommand /// KeyInputSet bound to an insert mode command | InsertBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * InsertCommand: InsertCommand /// KeyInputSet bound to a complex VisualCommand instance | ComplexVisualBinding of KeyInputSet: KeyInputSet * CommandFlags: CommandFlags * BindDataStorage: BindDataStorage<VisualCommand> with /// The raw command inputs member x.KeyInputSet = match x with | NormalBinding (value, _, _) -> value | MotionBinding (value, _, _) -> value | VisualBinding (value, _, _) -> value | InsertBinding (value, _, _) -> value | ComplexNormalBinding (value, _, _) -> value | ComplexVisualBinding (value, _, _) -> value /// The kind of the Command member x.CommandFlags = match x with | NormalBinding (_, value, _) -> value | MotionBinding (_, value, _) -> value | VisualBinding (_, value, _) -> value | InsertBinding (_, value, _) -> value | ComplexNormalBinding (_, value, _) -> value | ComplexVisualBinding (_, value, _) -> value /// Is the Repeatable flag set member x.IsRepeatable = Util.IsFlagSet x.CommandFlags CommandFlags.Repeatable /// Is the HandlesEscape flag set member x.HandlesEscape = Util.IsFlagSet x.CommandFlags CommandFlags.HandlesEscape /// Is the Movement flag set member x.IsMovement = Util.IsFlagSet x.CommandFlags CommandFlags.Movement /// Is the Special flag set member x.IsSpecial = Util.IsFlagSet x.CommandFlags CommandFlags.Special override x.ToString() = System.String.Format("{0} -> {1}", x.KeyInputSet, x.CommandFlags) /// Used to execute commands and ICommandUtil = /// Run a normal command abstract RunNormalCommand: command: NormalCommand -> commandData: CommandData -> CommandResult /// Run a visual command abstract RunVisualCommand: command: VisualCommand -> commandData: CommandData -> visualSpan: VisualSpan -> CommandResult /// Run a insert command abstract RunInsertCommand: command: InsertCommand -> CommandResult /// Run a command diff --git a/Src/VimCore/Modes_Visual_SelectMode.fs b/Src/VimCore/Modes_Visual_SelectMode.fs index 96409fb..3b5e31e 100644 --- a/Src/VimCore/Modes_Visual_SelectMode.fs +++ b/Src/VimCore/Modes_Visual_SelectMode.fs @@ -1,326 +1,325 @@ namespace Vim.Modes.Visual open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Operations open Microsoft.VisualStudio.Text.Editor open Vim open Vim.Modes type internal SelectMode ( _vimBufferData: IVimBufferData, _commonOperations: ICommonOperations, _motionUtil: IMotionUtil, _visualKind: VisualKind, _runner: ICommandRunner, _capture: IMotionCapture, _undoRedoOperations: IUndoRedoOperations, _selectionTracker: ISelectionTracker ) = let _globalSettings = _vimBufferData.LocalSettings.GlobalSettings let _vimTextBuffer = _vimBufferData.VimTextBuffer let _textBuffer = _vimBufferData.TextBuffer let _textView = _vimBufferData.TextView let _modeKind = match _visualKind with | VisualKind.Character -> ModeKind.SelectCharacter | VisualKind.Line -> ModeKind.SelectLine | VisualKind.Block -> ModeKind.SelectBlock /// Handles Ctrl+C/Ctrl+V/Ctrl+X a la $VIMRUNTIME/mswin.vim static let Commands = let visualSeq = seq { yield ("<C-g>", CommandFlags.Special, VisualCommand.SwitchModeOtherVisual) yield ("<C-x>", CommandFlags.Special, VisualCommand.CutSelection) yield ("<C-c>", CommandFlags.Special, VisualCommand.CopySelection) yield ("<C-v>", CommandFlags.Special, VisualCommand.CutSelectionAndPaste) yield ("<C-a>", CommandFlags.Special, VisualCommand.SelectAll) yield ("<LeftMouse>", CommandFlags.Special, VisualCommand.MoveCaretToMouse) yield ("<LeftDrag>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseDrag) yield ("<LeftRelease>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseRelease) yield ("<S-LeftMouse>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseClick) yield ("<2-LeftMouse>", CommandFlags.Special, VisualCommand.SelectWordOrMatchingTokenAtMousePoint) yield ("<3-LeftMouse>", CommandFlags.Special, VisualCommand.SelectLine) yield ("<4-LeftMouse>", CommandFlags.Special, VisualCommand.SelectBlock) // Multi-selection bindings not in Vim. yield ("<C-A-LeftMouse>", CommandFlags.Special, VisualCommand.AddCaretAtMousePoint) yield ("<C-A-2-LeftMouse>", CommandFlags.Special, VisualCommand.AddWordOrMatchingTokenAtMousePointToSelection) yield ("<C-A-Up>", CommandFlags.Special, VisualCommand.AddSelectionOnAdjacentLine Direction.Up) yield ("<C-A-Down>", CommandFlags.Special, VisualCommand.AddSelectionOnAdjacentLine Direction.Down) - yield ("<C-A-n>", CommandFlags.Special, VisualCommand.AddNextOccurrenceOfPrimarySelection) - yield ("<C-A-i>", CommandFlags.Special, VisualCommand.SplitSelectionIntoCarets) + yield ("<C-A-n>", CommandFlags.Special, VisualCommand.StartMultiSelection) } |> Seq.map (fun (str, flags, command) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.VisualBinding (keyInputSet, flags, command)) visualSeq /// A 'special key' is defined in :help keymodel as any of the following keys. Depending /// on the value of the keymodel setting they can affect the selection static let GetCaretMovement (keyInput: KeyInput) = let nonShiftModifiers = keyInput.KeyModifiers &&& ~~~VimKeyModifiers.Shift if nonShiftModifiers = VimKeyModifiers.None then match keyInput.Key with | VimKey.Up -> Some CaretMovement.Up | VimKey.Right -> Some CaretMovement.Right | VimKey.Down -> Some CaretMovement.Down | VimKey.Left -> Some CaretMovement.Left | VimKey.Home -> Some CaretMovement.Home | VimKey.End -> Some CaretMovement.End | VimKey.PageUp -> Some CaretMovement.PageUp | VimKey.PageDown -> Some CaretMovement.PageDown | _ -> None elif nonShiftModifiers = VimKeyModifiers.Control then match keyInput.Key with | VimKey.Up -> Some CaretMovement.ControlUp | VimKey.Right -> Some CaretMovement.ControlRight | VimKey.Down -> Some CaretMovement.ControlDown | VimKey.Left -> Some CaretMovement.ControlLeft | VimKey.Home -> Some CaretMovement.ControlHome | VimKey.End -> Some CaretMovement.ControlEnd | _ -> None else None /// Whether a key input corresponds to normal text static let IsTextKeyInput (keyInput: KeyInput) = Option.isSome keyInput.RawChar && not (CharUtil.IsControl keyInput.Char) && not (Util.IsFlagSet keyInput.KeyModifiers VimKeyModifiers.Alt) let mutable _builtCommands = false member x.CommandNames = x.EnsureCommandsBuilt() _runner.Commands |> Seq.map (fun command -> command.KeyInputSet) member this.KeyRemapMode = if _runner.IsWaitingForMoreInput then _runner.KeyRemapMode else KeyRemapMode.Visual member x.EnsureCommandsBuilt() = /// Whether a command is bound to a key that is not insertable text let isNonTextCommand (command: CommandBinding) = match command.KeyInputSet.FirstKeyInput with | None -> true | Some keyInput -> not (IsTextKeyInput keyInput) if not _builtCommands then let factory = CommandFactory(_commonOperations, _capture) // Add in the standard non-conflicting movement commands factory.CreateScrollCommands() |> Seq.filter isNonTextCommand |> Seq.append Commands |> Seq.iter _runner.Add _builtCommands <- true member x.CaretPoint = TextViewUtil.GetCaretPoint _textView member x.CaretVirtualPoint = TextViewUtil.GetCaretVirtualPoint _textView member x.CaretLine = TextViewUtil.GetCaretLine _textView member x.CurrentSnapshot = _textView.TextSnapshot member x.ShouldStopSelection (keyInput: KeyInput) = let hasShift = Util.IsFlagSet keyInput.KeyModifiers VimKeyModifiers.Shift let hasStopSelection = Util.IsFlagSet _globalSettings.KeyModelOptions KeyModelOptions.StopSelection not hasShift && hasStopSelection member x.ProcessCaretMovement caretMovement keyInput = fun () -> x.ProcessCaretMovementCore caretMovement keyInput |> ProcessResult.ToCommandResult |> _commonOperations.RunForAllSelections |> ProcessResult.OfCommandResult member x.ProcessCaretMovementCore caretMovement keyInput = let shouldStopSelection = x.ShouldStopSelection keyInput let isInclusive = _globalSettings.IsSelectionInclusive let shouldMimicNative = shouldStopSelection && not isInclusive let leaveSelectWithCaretAtPoint caretPoint = TextViewUtil.ClearSelection _textView _commonOperations.MoveCaretToVirtualPoint caretPoint ViewFlags.Standard ProcessResult.Handled ModeSwitch.SwitchPreviousMode if shouldMimicNative && caretMovement = CaretMovement.Left then // For a native exclusive selction, typing plain left leaves the // caret at the selection start point. leaveSelectWithCaretAtPoint _textView.Selection.Start elif shouldMimicNative && caretMovement = CaretMovement.Right then // For a native exclusive selction, typing plain right leaves the // caret at the selection end point. leaveSelectWithCaretAtPoint _textView.Selection.End else let anchorPoint = _textView.Selection.AnchorPoint TextViewUtil.ClearSelection _textView _commonOperations.MoveCaretWithArrow caretMovement |> ignore if shouldStopSelection then ProcessResult.Handled ModeSwitch.SwitchPreviousMode else // The caret moved so we need to update the selection _selectionTracker.UpdateSelectionWithAnchorPoint anchorPoint ProcessResult.Handled ModeSwitch.NoSwitch /// Overwrite the selection with the specified text member x.ProcessInput text linked = fun () -> x.ProcessInputCore text linked |> ProcessResult.ToCommandResult |> _commonOperations.RunForAllSelections |> ProcessResult.OfCommandResult /// The user hit an input key. Need to replace the current selection with /// the given text and put the caret just after the insert. This needs to /// be a single undo transaction member x.ProcessInputCore text linked = let replaceSelection (span: SnapshotSpan) text = fun () -> use edit = _textBuffer.CreateEdit() // First step is to replace the deleted text with the new one edit.Delete(span.Span) |> ignore edit.Insert(span.End.Position, text) |> ignore // Now move the caret past the insert point in the new // snapshot. We don't need to add one here (or even the length // of the insert text). The insert occurred at the exact point // we are tracking and we chose PointTrackingMode.Positive so // this will push the point past the insert edit.Apply() |> ignore _commonOperations.MapPointPositiveToCurrentSnapshot span.End |> TextViewUtil.MoveCaretToPoint _textView |> _undoRedoOperations.EditWithUndoTransaction "Replace" _textView // During undo we don't want the currently selected text to be // reselected as that would put the editor back into select mode. // Clear the selection now so that it's not recorderd in the undo // transaction and move the caret to the selection start let span = _textView.Selection.StreamSelectionSpan.SnapshotSpan TextViewUtil.ClearSelection _textView TextViewUtil.MoveCaretToPoint _textView span.Start if linked then let transaction = _undoRedoOperations.CreateLinkedUndoTransaction "Replace" try replaceSelection span text with | _ -> transaction.Dispose() reraise() let arg = ModeArgument.InsertWithTransaction transaction ProcessResult.Handled (ModeSwitch.SwitchModeWithArgument (ModeKind.Insert, arg)) else replaceSelection span text ProcessResult.Handled (ModeSwitch.SwitchMode ModeKind.Insert) member x.CanProcess (keyInput: KeyInput) = KeyInputUtil.IsCore keyInput && not keyInput.IsMouseKey || _runner.DoesCommandStartWith keyInput member x.Process (keyInputData: KeyInputData) = let keyInput = keyInputData.KeyInput let processResult = if keyInput = KeyInputUtil.EscapeKey then ProcessResult.Handled ModeSwitch.SwitchPreviousMode elif keyInput = KeyInputUtil.EnterKey then let caretPoint = TextViewUtil.GetCaretPoint _textView let text = _commonOperations.GetNewLineText caretPoint x.ProcessInput text true elif keyInput.Key = VimKey.Delete || keyInput.Key = VimKey.Back then x.ProcessInput "" false |> ignore ProcessResult.Handled ModeSwitch.SwitchPreviousMode elif keyInput = KeyInputUtil.CharWithControlToKeyInput 'o' then x.ProcessVisualModeOneCommand keyInput else match GetCaretMovement keyInput with | Some caretMovement -> x.ProcessCaretMovement caretMovement keyInput | None -> if IsTextKeyInput keyInput then x.ProcessInput (StringUtil.OfChar keyInput.Char) true else match _runner.Run keyInput with | BindResult.NeedMoreInput _ -> ProcessResult.HandledNeedMoreInput | BindResult.Complete commandRanData -> match commandRanData.CommandResult with | CommandResult.Error -> _selectionTracker.UpdateSelection() | CommandResult.Completed modeSwitch -> match modeSwitch with | ModeSwitch.NoSwitch -> _selectionTracker.UpdateSelection() | ModeSwitch.SwitchMode _ -> () | ModeSwitch.SwitchModeWithArgument _ -> () | ModeSwitch.SwitchPreviousMode -> () | ModeSwitch.SwitchModeOneTimeCommand _ -> () ProcessResult.OfCommandResult commandRanData.CommandResult | BindResult.Error -> _commonOperations.Beep() ProcessResult.NotHandled | BindResult.Cancelled -> _selectionTracker.UpdateSelection() ProcessResult.Handled ModeSwitch.NoSwitch /// Restore or clear the selection depending on the next mode if processResult.IsAnySwitchToVisual then _selectionTracker.UpdateSelection() elif processResult.IsAnySwitch then TextViewUtil.ClearSelection _textView _textView.Selection.Mode <- TextSelectionMode.Stream processResult /// Enter visual mode for a single command. member x.ProcessVisualModeOneCommand keyInput = match VisualKind.OfModeKind _modeKind with | Some visualKind -> let modeKind = visualKind.VisualModeKind let modeSwitch = ModeSwitch.SwitchModeOneTimeCommand modeKind ProcessResult.Handled modeSwitch | None -> ProcessResult.Error member x.OnEnter modeArgument = x.EnsureCommandsBuilt() _selectionTracker.RecordCaretTrackingPoint modeArgument _selectionTracker.Start() member x.OnLeave() = _runner.ResetState() _selectionTracker.Stop() member x.OnClose() = () member x.SyncSelection() = if _selectionTracker.IsRunning then _selectionTracker.Stop() _selectionTracker.Start() interface ISelectMode with member x.SyncSelection() = x.SyncSelection() interface IMode with member x.VimTextBuffer = _vimTextBuffer member x.CommandNames = Commands |> Seq.map (fun binding -> binding.KeyInputSet) member x.ModeKind = _modeKind member x.CanProcess keyInput = x.CanProcess keyInput member x.Process keyInputData = x.Process keyInputData member x.OnEnter modeArgument = x.OnEnter modeArgument member x.OnLeave () = x.OnLeave() member x.OnClose() = x.OnClose() diff --git a/Src/VimCore/Modes_Visual_VisualMode.fs b/Src/VimCore/Modes_Visual_VisualMode.fs index 844fbdb..46d890c 100644 --- a/Src/VimCore/Modes_Visual_VisualMode.fs +++ b/Src/VimCore/Modes_Visual_VisualMode.fs @@ -1,348 +1,347 @@ #light namespace Vim.Modes.Visual open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Operations open Microsoft.VisualStudio.Text.Editor open Vim open Vim.Modes type internal VisualMode ( _vimBufferData: IVimBufferData, _operations: ICommonOperations, _motionUtil: IMotionUtil, _visualKind: VisualKind, _runner: ICommandRunner, _capture: IMotionCapture, _selectionTracker: ISelectionTracker ) = let _vimTextBuffer = _vimBufferData.VimTextBuffer let _textView = _vimBufferData.TextView let _textBuffer = _vimTextBuffer.TextBuffer let _globalSettings = _vimTextBuffer.GlobalSettings let _eventHandlers = DisposableBag() let _operationKind, _modeKind = match _visualKind with | VisualKind.Character -> (OperationKind.CharacterWise, ModeKind.VisualCharacter) | VisualKind.Line -> (OperationKind.LineWise, ModeKind.VisualLine) | VisualKind.Block -> (OperationKind.CharacterWise, ModeKind.VisualBlock) // Command to show when entering command from Visual Mode static let CommandFromVisualModeString = "'<,'>" /// Get a mark and use the provided 'func' to create a Motion value static let BindMark func = let bindFunc (keyInput: KeyInput) = match Mark.OfChar keyInput.Char with | None -> BindResult<NormalCommand>.Error | Some localMark -> BindResult<_>.Complete (func localMark) let bindData = { KeyRemapMode = KeyRemapMode.None BindFunction = bindFunc } BindDataStorage<_>.Simple bindData static let SharedCommands = let visualSeq = seq { yield ("c", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeSelection) yield ("C", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeLineSelection true) yield ("d", CommandFlags.Repeatable, VisualCommand.DeleteSelection) yield ("D", CommandFlags.Repeatable, VisualCommand.DeleteLineSelection) yield ("gf", CommandFlags.None, VisualCommand.GoToFileInSelection) yield ("gJ", CommandFlags.Repeatable, VisualCommand.JoinSelection JoinKind.KeepEmptySpaces) yield ("gp", CommandFlags.Repeatable, VisualCommand.PutOverSelection true) yield ("gP", CommandFlags.Repeatable, VisualCommand.PutOverSelection true) yield ("g?", CommandFlags.Repeatable, VisualCommand.ChangeCase ChangeCharacterKind.Rot13) yield ("gn", CommandFlags.Repeatable, VisualCommand.ExtendSelectionToNextMatch SearchPath.Forward) yield ("gN", CommandFlags.Repeatable, VisualCommand.ExtendSelectionToNextMatch SearchPath.Backward) yield ("J", CommandFlags.Repeatable, VisualCommand.JoinSelection JoinKind.RemoveEmptySpaces) yield ("o", CommandFlags.Movement ||| CommandFlags.ResetAnchorPoint, VisualCommand.InvertSelection false) yield ("O", CommandFlags.Movement ||| CommandFlags.ResetAnchorPoint, VisualCommand.InvertSelection true) yield ("p", CommandFlags.Repeatable, VisualCommand.PutOverSelection false) yield ("P", CommandFlags.Repeatable, VisualCommand.PutOverSelection false) yield ("R", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeLineSelection false) yield ("s", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeSelection) yield ("S", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeLineSelection false) yield ("u", CommandFlags.Repeatable, VisualCommand.ChangeCase ChangeCharacterKind.ToLowerCase) yield ("U", CommandFlags.Repeatable, VisualCommand.ChangeCase ChangeCharacterKind.ToUpperCase) yield ("v", CommandFlags.Special, VisualCommand.SwitchModeVisual VisualKind.Character) yield ("V", CommandFlags.Special, VisualCommand.SwitchModeVisual VisualKind.Line) yield ("x", CommandFlags.Repeatable, VisualCommand.DeleteSelection) yield ("X", CommandFlags.Repeatable, VisualCommand.DeleteLineSelection) yield ("y", CommandFlags.ResetCaret, VisualCommand.YankSelection) yield ("Y", CommandFlags.ResetCaret, VisualCommand.YankLineSelection) yield ("zf", CommandFlags.None, VisualCommand.FoldSelection) yield ("zF", CommandFlags.None, VisualCommand.FoldSelection) yield ("zo", CommandFlags.Special, VisualCommand.OpenFoldInSelection) yield ("zO", CommandFlags.Special, VisualCommand.OpenAllFoldsInSelection) yield ("zc", CommandFlags.Special, VisualCommand.CloseFoldInSelection) yield ("zC", CommandFlags.Special, VisualCommand.CloseAllFoldsInSelection) yield ("za", CommandFlags.Special, VisualCommand.ToggleFoldInSelection) yield ("zA", CommandFlags.Special, VisualCommand.ToggleAllFoldsInSelection) yield ("zd", CommandFlags.Special, VisualCommand.DeleteAllFoldsInSelection) yield ("zD", CommandFlags.Special, VisualCommand.DeleteAllFoldsInSelection) yield ("<C-c>", CommandFlags.Special, VisualCommand.CancelOperation) yield ("<C-q>", CommandFlags.Special, VisualCommand.SwitchModeVisual VisualKind.Block) yield ("<C-v>", CommandFlags.Special, VisualCommand.SwitchModeVisual VisualKind.Block) yield ("<S-i>", CommandFlags.Special, VisualCommand.SwitchModeInsert VisualInsertKind.Start) yield ("<S-a>", CommandFlags.Special, VisualCommand.SwitchModeInsert VisualInsertKind.End) yield ("<C-g>", CommandFlags.Special, VisualCommand.SwitchModeOtherVisual) yield ("<C-w>gf", CommandFlags.None, VisualCommand.GoToFileInSelectionInNewWindow) yield ("<Del>", CommandFlags.Repeatable, VisualCommand.DeleteSelection) yield ("<lt>", CommandFlags.Repeatable, VisualCommand.ShiftLinesLeft) yield (">", CommandFlags.Repeatable, VisualCommand.ShiftLinesRight) yield ("~", CommandFlags.Repeatable, VisualCommand.ChangeCase ChangeCharacterKind.ToggleCase) yield ("=", CommandFlags.Repeatable, VisualCommand.FormatCodeLines) yield ("gq", CommandFlags.Repeatable, VisualCommand.FormatTextLines false) yield ("gw", CommandFlags.Repeatable, VisualCommand.FormatTextLines true) yield ("gx", CommandFlags.Repeatable, VisualCommand.OpenLinkInSelection) yield ("!", CommandFlags.Repeatable, VisualCommand.FilterLines) yield ("<C-a>", CommandFlags.Repeatable, VisualCommand.AddToSelection false) yield ("<C-x>", CommandFlags.Repeatable, VisualCommand.SubtractFromSelection false) yield ("g<C-a>", CommandFlags.Repeatable, VisualCommand.AddToSelection true) yield ("g<C-x>", CommandFlags.Repeatable, VisualCommand.SubtractFromSelection true) yield ("<LeftMouse>", CommandFlags.Special, VisualCommand.MoveCaretToMouse) yield ("<LeftDrag>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseDrag) yield ("<LeftRelease>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseRelease) yield ("<S-LeftMouse>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseClick) yield ("<2-LeftMouse>", CommandFlags.Special, VisualCommand.SelectWordOrMatchingTokenAtMousePoint) yield ("<3-LeftMouse>", CommandFlags.Special, VisualCommand.SelectLine) yield ("<4-LeftMouse>", CommandFlags.Special, VisualCommand.SelectBlock) // Multi-selection bindings not in Vim. yield ("<C-A-LeftMouse>", CommandFlags.Special, VisualCommand.AddCaretAtMousePoint) yield ("<C-A-2-LeftMouse>", CommandFlags.Special, VisualCommand.AddWordOrMatchingTokenAtMousePointToSelection) yield ("<C-A-Up>", CommandFlags.Special, VisualCommand.AddSelectionOnAdjacentLine Direction.Up) yield ("<C-A-Down>", CommandFlags.Special, VisualCommand.AddSelectionOnAdjacentLine Direction.Down) - yield ("<C-A-n>", CommandFlags.Special, VisualCommand.AddNextOccurrenceOfPrimarySelection) - yield ("<C-A-i>", CommandFlags.Special, VisualCommand.SplitSelectionIntoCarets) + yield ("<C-A-n>", CommandFlags.Special, VisualCommand.StartMultiSelection) } |> Seq.map (fun (str, flags, command) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.VisualBinding (keyInputSet, flags, command)) let complexSeq = seq { yield ("r", CommandFlags.Repeatable, BindData<_>.CreateForKeyInput KeyRemapMode.None VisualCommand.ReplaceSelection) } |> Seq.map (fun (str, flags, bindCommand) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str let storage = BindDataStorage.Simple bindCommand CommandBinding.ComplexVisualBinding (keyInputSet, flags, storage)) let normalSeq = seq { yield ("gv", CommandFlags.Special, NormalCommand.SwitchPreviousVisualMode) yield ("zE", CommandFlags.Special, NormalCommand.DeleteAllFoldsInBuffer) yield ("zM", CommandFlags.Special, NormalCommand.CloseAllFolds) yield ("zR", CommandFlags.Special, NormalCommand.OpenAllFolds) yield ("[p", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield ("[P", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield ("]p", CommandFlags.Repeatable, NormalCommand.PutAfterCaretWithIndent) yield ("]P", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield (":", CommandFlags.Special, NormalCommand.SwitchMode (ModeKind.Command, (ModeArgument.PartialCommand CommandFromVisualModeString))) } |> Seq.map (fun (str, flags, command) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.NormalBinding (keyInputSet, flags, command)) let normalComplexSeq = seq { yield ("'", CommandFlags.Movement, BindMark NormalCommand.JumpToMarkLine) yield ("`", CommandFlags.Movement, BindMark NormalCommand.JumpToMark) } |> Seq.map (fun (str, flags, storage) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.ComplexNormalBinding (keyInputSet, flags, storage)) Seq.append visualSeq complexSeq |> Seq.append normalSeq |> Seq.append normalComplexSeq |> List.ofSeq let mutable _builtCommands = false member x.CurrentSnapshot = _textBuffer.CurrentSnapshot member x.CaretPoint = TextViewUtil.GetCaretPoint _textView member x.CanProcess (keyInput: KeyInput) = KeyInputUtil.IsCore keyInput && not keyInput.IsMouseKey ||_runner.DoesCommandStartWith keyInput member x.CommandNames = x.EnsureCommandsBuilt() _runner.Commands |> Seq.map (fun command -> command.KeyInputSet) member this.KeyRemapMode = if _runner.IsWaitingForMoreInput then _runner.KeyRemapMode else KeyRemapMode.Visual member x.SelectedSpan = (TextSelectionUtil.GetStreamSelectionSpan _textView.Selection).SnapshotSpan member x.EnsureCommandsBuilt() = if not _builtCommands then let factory = CommandFactory(_operations, _capture) // Add in the standard commands factory.CreateMovementCommands() |> Seq.append (factory.CreateMovementTextObjectCommands()) |> Seq.append (factory.CreateScrollCommands()) |> Seq.append SharedCommands |> Seq.iter _runner.Add // Add in macro editing factory.CreateMacroEditCommands _runner _vimTextBuffer.Vim.MacroRecorder _eventHandlers _builtCommands <- true member x.OnEnter modeArgument = x.EnsureCommandsBuilt() _selectionTracker.RecordCaretTrackingPoint modeArgument _selectionTracker.Start() member x.OnClose() = _eventHandlers.DisposeAll() /// Called when the Visual Mode is left. Need to update the LastVisualSpan based on our selection member x.OnLeave() = _runner.ResetState() _selectionTracker.Stop() /// The current Visual Selection member x.VisualSelection = let selectionKind = _globalSettings.SelectionKind let tabStop = _vimBufferData.LocalSettings.TabStop let useVirtualSpace = _vimTextBuffer.UseVirtualSpace let visualSelection = VisualSelection.CreateForVirtualSelection _textView _visualKind selectionKind tabStop useVirtualSpace let isMaintainingEndOfLine = _vimBufferData.MaintainCaretColumn.IsMaintainingEndOfLine visualSelection.AdjustWithEndOfLine isMaintainingEndOfLine member x.Process (keyInputData: KeyInputData) = let keyInput = keyInputData.KeyInput // Save the last visual selection at the global level for use with [count]V|v except // in the case of <Esc>. This <Esc> exception is not a documented behavior but exists // experimentally. match keyInput, _vimTextBuffer.LastVisualSelection with | keyInput, Some lastVisualSelection when keyInput <> KeyInputUtil.EscapeKey -> let vimData = _vimBufferData.Vim.VimData match StoredVisualSelection.CreateFromVisualSpan lastVisualSelection.VisualSpan with | None -> () | Some v -> vimData.LastVisualSelection <- Some v | _ -> () let result = if keyInput = KeyInputUtil.EscapeKey && x.ShouldHandleEscape then ProcessResult.Handled ModeSwitch.SwitchPreviousMode else match _runner.Run keyInput with | BindResult.NeedMoreInput _ -> _selectionTracker.UpdateSelection() ProcessResult.HandledNeedMoreInput | BindResult.Complete commandRanData -> if Util.IsFlagSet commandRanData.CommandBinding.CommandFlags CommandFlags.ResetCaret then x.ResetCaret() if Util.IsFlagSet commandRanData.CommandBinding.CommandFlags CommandFlags.ResetAnchorPoint then match _vimBufferData.VisualAnchorPoint |> OptionUtil.map2 (TrackingPointUtil.GetPoint x.CurrentSnapshot) with | None -> () | Some anchorPoint -> let anchorPoint = VirtualSnapshotPointUtil.OfPoint anchorPoint _selectionTracker.UpdateSelectionWithAnchorPoint anchorPoint match commandRanData.CommandResult with | CommandResult.Error -> _selectionTracker.UpdateSelection() | CommandResult.Completed modeSwitch -> match modeSwitch with | ModeSwitch.NoSwitch -> _selectionTracker.UpdateSelection() | ModeSwitch.SwitchMode(_) -> () | ModeSwitch.SwitchModeWithArgument(_,_) -> () | ModeSwitch.SwitchPreviousMode -> () | ModeSwitch.SwitchModeOneTimeCommand _ -> () ProcessResult.OfCommandResult commandRanData.CommandResult | BindResult.Error -> _selectionTracker.UpdateSelection() _operations.Beep() if keyInput.IsMouseKey then ProcessResult.NotHandled else ProcessResult.Handled ModeSwitch.NoSwitch | BindResult.Cancelled -> _selectionTracker.UpdateSelection() ProcessResult.Handled ModeSwitch.NoSwitch // If we are switching out Visual Mode then reset the selection. Only do this if // we are the active IMode. It's very possible that we were switched out already // as part of a complex command if result.IsAnySwitch && _selectionTracker.IsRunning then // On teardown we will get calls to Stop when the view is closed. It's invalid to access // the selection at that point if not _textView.IsClosed then if result.IsAnySwitchToVisual then _selectionTracker.UpdateSelection() elif not result.IsAnySwitchToCommand then TextViewUtil.ClearSelection _textView _textView.Selection.Mode <- TextSelectionMode.Stream result /// Certain operations cause the caret to be reset to it's position before visual mode /// started once visual mode is complete (y for example). This function handles that member x.ResetCaret() = // Calculate the start point of the selection let startPoint = match _vimBufferData.VisualCaretStartPoint with | None -> None | Some trackingPoint -> TrackingPointUtil.GetPoint x.CurrentSnapshot trackingPoint match startPoint with | None -> // If we couldn't calculate a start point then there is just nothing to do. This // really shouldn't happen though () | Some startPoint -> // Calculate the actual point to use. If the selection turned backwards then we // prefer the current caret over the original let point = if startPoint.Position < x.CaretPoint.Position then startPoint else x.CaretPoint _operations.MoveCaretToPoint point ViewFlags.Standard member x.ShouldHandleEscape = not _runner.IsHandlingEscape member x.SyncSelection() = if _selectionTracker.IsRunning then _selectionTracker.Stop() _selectionTracker.Start() interface IMode with member x.VimTextBuffer = _vimTextBuffer member x.CommandNames = x.CommandNames member x.ModeKind = _modeKind member x.CanProcess keyInput = x.CanProcess keyInput member x.Process keyInputData = x.Process keyInputData member x.OnEnter modeArgument = x.OnEnter modeArgument member x.OnLeave () = x.OnLeave() member x.OnClose() = x.OnClose() interface IVisualMode with member x.CommandRunner = _runner member x.KeyRemapMode = x.KeyRemapMode member x.InCount = _runner.InCount member x.VisualSelection = x.VisualSelection member x.SyncSelection () = x.SyncSelection() diff --git a/Test/VimCoreTest/MultiSelectionIntegrationTest.cs b/Test/VimCoreTest/MultiSelectionIntegrationTest.cs index 2c18390..fb82829 100644 --- a/Test/VimCoreTest/MultiSelectionIntegrationTest.cs +++ b/Test/VimCoreTest/MultiSelectionIntegrationTest.cs @@ -97,874 +97,874 @@ namespace Vim.UnitTest Assert.Equal(expectedSpans, SelectedSpans); } private void AssertSelectionsAdjustCaret(params SelectionSpan[] expectedSpans) { if (!_globalSettings.IsSelectionInclusive) { AssertSelections(expectedSpans); return; } var adjustedExpectedSpans = expectedSpans.Select(x => x.AdjustCaretForInclusive()) .ToArray(); Assert.Equal(adjustedExpectedSpans, SelectedSpans); } private void AssertSelectionsAdjustEnd(params SelectionSpan[] expectedSpans) { if (!_globalSettings.IsSelectionInclusive) { AssertSelections(expectedSpans); return; } var adjustedExpectedSpans = expectedSpans.Select(x => x.AdjustEndForInclusive()) .ToArray(); Assert.Equal(adjustedExpectedSpans, SelectedSpans); } private void AssertLines(params string[] lines) { Assert.Equal(lines, _textBuffer.GetLines().ToArray()); } public sealed class MockTest : MultiSelectionIntegrationTest { /// <summary> /// Mock inftrastructure should use the real text view for the /// primary selection and the internal data structure for the /// secondary selection /// </summary> [WpfFact] public void Basic() { Create("cat", "bat", ""); SetCaretPoints( _textView.GetVirtualPointInLine(0, 1), _textView.GetVirtualPointInLine(1, 1)); // Verify real caret and real selection. Assert.Equal( _textView.GetVirtualPointInLine(0, 1), _textView.GetCaretVirtualPoint()); Assert.Equal( new VirtualSnapshotSpan(new SnapshotSpan(_textView.GetPointInLine(0, 1), 0)), _textView.GetVirtualSelectionSpan()); // Verify secondary selection agrees with mock vim host. Assert.Single(_mockMultiSelectionUtil.SecondarySelectedSpans); Assert.Equal( new SelectionSpan(_textView.GetVirtualPointInLine(1, 1)), _mockMultiSelectionUtil.SecondarySelectedSpans[0]); } } public sealed class MultiSelectionTrackerTest : MultiSelectionIntegrationTest { [WpfFact] public void RestoreCarets() { Create("abc def ghi", "jkl mno pqr", ""); _globalSettings.StartOfLine = false; SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation(":1<CR>"); AssertCarets(GetPoint(0, 4), GetPoint(1, 4)); } [WpfFact] public void MoveCarets() { Create("abc def ghi", "jkl mno pqr", "stu vwx yz.", ""); _globalSettings.StartOfLine = false; SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation(":2<CR>"); AssertCarets(GetPoint(1, 4), GetPoint(2, 4)); } [WpfTheory, InlineData(false), InlineData(true)] public void ExternalSelection(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); // Primary selection. _textView.Caret.MoveTo(GetPoint(0, 7)); _textView.Selection.Select(GetPoint(0, 4), GetPoint(0, 7)); DoEvents(); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // Secondary selection. SetSelectedSpans( SelectedSpans[0], GetPoint(1, 7).GetSelectedSpan(-3, 0, false)); // 'mno|*' DoEvents(); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(1, 7).GetSelectedSpan(-3, 0, false)); // 'mno|*' or 'mn|o*' } } public sealed class AddCaretTest : MultiSelectionIntegrationTest { /// <summary> /// Using alt-click adds a new caret /// </summary> [WpfFact] public void AddCaret() { Create("abc def ghi", "jkl mno pqr", ""); _textView.SetVisibleLineCount(2); SetCaretPoints(GetPoint(0, 4)); _testableMouseDevice.Point = GetPoint(1, 8).Position; // 'g' in 'ghi' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease>"); AssertCarets(GetPoint(0, 4), GetPoint(1, 8)); } [WpfFact] public void RemovePrimaryCaret() { Create("abc def ghi", "jkl mno pqr", ""); _textView.SetVisibleLineCount(2); SetCaretPoints(GetPoint(0, 4)); _testableMouseDevice.Point = GetPoint(1, 8).Position; // 'g' in 'ghi' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease>"); AssertCarets(GetPoint(0, 4), GetPoint(1, 8)); _testableMouseDevice.Point = GetPoint(0, 4).Position; // 'd' in 'def' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease>"); AssertCarets(GetPoint(1, 8)); } [WpfFact] public void RemoveSecondaryCaret() { Create("abc def ghi", "jkl mno pqr", ""); _textView.SetVisibleLineCount(2); SetCaretPoints(GetPoint(0, 4)); _testableMouseDevice.Point = GetPoint(1, 8).Position; // 'g' in 'ghi' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease>"); AssertCarets(GetPoint(0, 4), GetPoint(1, 8)); ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease>"); // 'g' in 'ghi' AssertCarets(GetPoint(0, 4)); } [WpfFact] public void RemoveOnlyCaret() { Create("abc def ghi", "jkl mno pqr", ""); _textView.SetVisibleLineCount(2); SetCaretPoints(GetPoint(0, 4)); _testableMouseDevice.Point = GetPoint(0, 4).Position; // 'd' in 'def' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease>"); AssertCarets(GetPoint(0, 4)); } /// <summary> /// Using ctrl-alt-arrow adds a new caret /// </summary> [WpfFact] public void AddOnLineAbove() { Create("abc def ghi", "jkl mno pqr", ""); _textView.Caret.MoveTo(GetPoint(1, 4)); ProcessNotation("<C-A-Up>"); AssertCarets(GetPoint(1, 4), GetPoint(0, 4)); } /// <summary> /// Using ctrl-alt-arrow adds a new caret /// </summary> [WpfFact] public void AddOnLineBelow() { Create("abc def ghi", "jkl mno pqr", ""); _textView.Caret.MoveTo(GetPoint(0, 4)); ProcessNotation("<C-A-Down>"); AssertCarets(GetPoint(0, 4), GetPoint(1, 4)); } /// <summary> /// Using ctrl-alt-arrow adds a new caret /// </summary> [WpfFact] public void AddTwoAboveAndBelow() { Create( "abc def ghi", "jkl mno pqr", "abc def ghi", "jkl mno pqr", "abc def ghi", "jkl mno pqr", ""); _textView.Caret.MoveTo(GetPoint(2, 4)); ProcessNotation("<C-A-Up><C-A-Up><C-A-Down><C-A-Down>"); AssertCarets( GetPoint(2, 4), GetPoint(0, 4), GetPoint(1, 4), GetPoint(3, 4), GetPoint(4, 4)); } } public sealed class NormalModeTest : MultiSelectionIntegrationTest { /// <summary> /// Test clearing carets with escape /// </summary> [WpfFact] public void ClearCarets() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("<Esc>"); AssertCarets(GetPoint(0, 4)); } /// <summary> /// Test cancelling with control-C /// </summary> [WpfFact] public void CancelOperation() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("<C-C>"); AssertCarets(GetPoint(0, 4)); } /// <summary> /// Test restoring carets /// </summary> [WpfFact] public void RestoreCarets() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("<C-C>"); AssertCarets(GetPoint(0, 4)); ProcessNotation("<C-A-p>"); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); } /// <summary> /// Test moving the caret /// </summary> [WpfFact] public void Motion() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("w"); AssertCarets(GetPoint(0, 8), GetPoint(1, 8)); } /// <summary> /// Test inserting text /// </summary> [WpfFact] public void Insert() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("ixxx <Esc>"); AssertLines("abc xxx def ghi", "jkl xxx mno pqr", ""); AssertCarets(GetPoint(0, 7), GetPoint(1, 7)); } /// <summary> /// Test undoing inserted text /// </summary> [WpfFact] public void UndoInsert() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("ixxx <Esc>"); AssertLines("abc xxx def ghi", "jkl xxx mno pqr", ""); AssertCarets(GetPoint(0, 7), GetPoint(1, 7)); ProcessNotation("u"); AssertLines("abc def ghi", "jkl mno pqr", ""); AssertCarets(GetPoint(0, 4), GetPoint(1, 4)); } /// <summary> /// Test repeating inserted text /// </summary> [WpfFact] public void RepeatInsert() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("ixxx <Esc>ww."); AssertLines("abc xxx def xxx ghi", "jkl xxx mno xxx pqr", ""); AssertCarets(GetPoint(0, 15), GetPoint(1, 15)); } /// <summary> /// Test deleting the word at the caret /// </summary> [WpfFact] public void Delete() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("dw"); AssertLines("abc ghi", "jkl pqr", ""); AssertCarets(GetPoint(0, 4), GetPoint(1, 4)); } /// <summary> /// Test changing the word at the caret /// </summary> [WpfFact] public void Change() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("cwxxx<Esc>"); AssertLines("abc xxx ghi", "jkl xxx pqr", ""); AssertCarets(GetPoint(0, 6), GetPoint(1, 6)); } /// <summary> /// Test putting before word at the caret /// </summary> [WpfFact] public void Put() { Create("abc def ghi", "jkl mno pqr", ""); ProcessNotation("yw"); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("wP"); AssertLines("abc def abc ghi", "jkl mno abc pqr", ""); AssertCarets(GetPoint(0, 11), GetPoint(1, 11)); } /// <summary> /// Test deleting and putting the word at the caret /// </summary> [WpfTheory, InlineData(""), InlineData("unnamed")] public void DeleteAndPut(string clipboardSetting) { Create("abc def ghi jkl", "mno pqr stu vwx", ""); _globalSettings.Clipboard = clipboardSetting; SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("dwwP"); AssertLines("abc ghi def jkl", "mno stu pqr vwx", ""); AssertCarets(GetPoint(0, 11), GetPoint(1, 11)); } } public sealed class VisualCharacterModeTest : MultiSelectionIntegrationTest { /// <summary> /// Test entering visual character mode /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void Enter(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("v"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustEnd( GetPoint(0, 4).GetSelectedSpan(0, 0, false), // '|*'def or '|d*'ef GetPoint(1, 4).GetSelectedSpan(0, 0, false)); // '|*'mno or 'm*'no } /// <summary> /// Test moving the caret forward /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void MotionForward(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("vw"); AssertSelectionsAdjustEnd( GetPoint(0, 8).GetSelectedSpan(-4, 0, false), // 'def |' or 'def |g*' GetPoint(1, 8).GetSelectedSpan(-4, 0, false)); // 'mno |' or 'mno |p*' } /// <summary> /// Test adding a selection on an adjacent line /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void AddSelection(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4)); ProcessNotation("vw<C-A-Down>"); AssertSelectionsAdjustEnd( GetPoint(0, 8).GetSelectedSpan(-4, 0, false), // 'def |' or 'def |g*' GetPoint(1, 8).GetSelectedSpan(-4, 0, false)); // 'mno |' or 'mno |p*' } /// <summary> /// Test moving the caret backward /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void MotionBackward(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 8), GetPoint(1, 8)); ProcessNotation("vb"); AssertSelectionsAdjustEnd( GetPoint(0, 4).GetSelectedSpan(0, 4, true), // '|def ' GetPoint(1, 4).GetSelectedSpan(0, 4, true)); // '|mno ' } /// <summary> /// Motion through zero width /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void MotionThroughZeroWidth(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("vwbb"); AssertSelectionsAdjustEnd( GetPoint(0, 0).GetSelectedSpan(0, 4, true), // '|abc ' GetPoint(1, 0).GetSelectedSpan(0, 4, true)); // '|jkl ' } /// <summary> /// Test deleting text /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void Delete(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("veld"); AssertLines("abc ghi", "jkl pqr", ""); AssertCarets(GetPoint(0, 4), GetPoint(1, 4)); } /// <summary> /// Test changing text /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void Change(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("vec"); AssertLines("abc ghi", "jkl pqr", ""); AssertCarets(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("xxx<Esc>"); AssertLines("abc xxx ghi", "jkl xxx pqr", ""); AssertCarets(GetPoint(0, 6), GetPoint(1, 6)); } /// <summary> /// Test changing four lines of text /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void ChangeFourLines(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4), GetPoint(2, 4), GetPoint(3, 4)); ProcessNotation("vec"); AssertLines("abc ghi", "jkl pqr", "abc ghi", "jkl pqr", ""); AssertCarets(GetPoint(0, 4), GetPoint(1, 4), GetPoint(2, 4), GetPoint(3, 4)); ProcessNotation("xxx<Esc>"); AssertLines("abc xxx ghi", "jkl xxx pqr", "abc xxx ghi", "jkl xxx pqr", ""); AssertCarets(GetPoint(0, 6), GetPoint(1, 6), GetPoint(2, 6), GetPoint(3, 6)); } /// <summary> /// Spacing back and forth through the centerline /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void SpacingBackAndForth(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("vhh"); AssertSelectionsAdjustEnd( GetPoint(0, 2).GetSelectedSpan(0, 2, true), // '*|c ' GetPoint(1, 2).GetSelectedSpan(0, 2, true)); // '*|l ' ProcessNotation("llll"); AssertSelectionsAdjustEnd( GetPoint(0, 6).GetSelectedSpan(-2, 0, false), // 'de|*' GetPoint(1, 6).GetSelectedSpan(-2, 0, false)); // 'jk|*' ProcessNotation("hhhh"); AssertSelectionsAdjustEnd( GetPoint(0, 2).GetSelectedSpan(0, 2, true), // '*|c ' GetPoint(1, 2).GetSelectedSpan(0, 2, true)); // '*|l ' } /// <summary> /// Split selection into carets /// </summary> [WpfFact] public void SplitSelection() { Create(" abc def ghi", " jkl mno pqr", " stu vwx yz.", ""); SetCaretPoints(GetPoint(0, 4)); - ProcessNotation("vjj<C-A-i>"); + ProcessNotation("vjj<C-A-n>"); AssertCarets(GetPoint(0, 4), GetPoint(1, 0), GetPoint(2, 0)); } /// <summary> /// Invert anchor and active point in all selections /// </summary> /// <param name="isInclusive"></param> [WpfTheory, InlineData(false), InlineData(true)] public void InvertSelection(bool isInclusive) { Create(isInclusive, "abc def ghi", "jkl mno pqr", "stu vwx yz.", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4), GetPoint(2, 4)); ProcessNotation("ve"); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(1, 7).GetSelectedSpan(-3, 0, false), // 'mno|*' or 'mn|o*' GetPoint(2, 7).GetSelectedSpan(-3, 0, false)); // 'vwx|*' or 'vw|x*' ProcessNotation("o"); AssertSelectionsAdjustCaret( GetPoint(0, 4).GetSelectedSpan(0, 3, true), // '*|def' GetPoint(1, 4).GetSelectedSpan(0, 3, true), // '*|mno' GetPoint(2, 4).GetSelectedSpan(0, 3, true)); // '*|vwx' ProcessNotation("o"); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(1, 7).GetSelectedSpan(-3, 0, false), // 'mno|*' or 'mn|o*' GetPoint(2, 7).GetSelectedSpan(-3, 0, false)); // 'vwx|*' or 'vw|x*' } /// <summary> /// Using double-click should revert to a single selection /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void SelectWord(bool isInclusive) { Create(isInclusive, "abc def ghi jkl", "mno pqr stu vwx", ""); _textView.SetVisibleLineCount(2); SetCaretPoints(GetPoint(0, 0), GetPoint(1, 0)); _testableMouseDevice.Point = GetPoint(0, 5).Position; // 'e' in 'def' ProcessNotation("<LeftMouse><LeftRelease><2-LeftMouse><LeftRelease>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' } /// <summary> /// Using ctrl-alt-double-click should add a word to the selection /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void AddWordToSelection(bool isInclusive) { Create(isInclusive, "abc def ghi jkl", "mno pqr stu vwx", ""); _textView.SetVisibleLineCount(2); // First double-click. _testableMouseDevice.Point = GetPoint(0, 5).Position; // 'e' in 'def' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease><C-A-2-LeftMouse><C-A-LeftRelease>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // Second double-click. _testableMouseDevice.Point = GetPoint(1, 9).Position; // 't' in 'stu' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease><C-A-2-LeftMouse><C-A-LeftRelease>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(1, 11).GetSelectedSpan(-3, 0, false)); // 'stu|*' or 'st|u*' } /// <summary> /// Adding the next occurrence of the primary selection should wrap /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void AddNextOccurrence(bool isInclusive) { Create(isInclusive, "abc def ghi", "abc def ghi", "abc def ghi", ""); SetCaretPoints(GetPoint(1, 5)); // Select word. ProcessNotation("<C-A-N>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(1, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // Select next occurrence below. ProcessNotation("<C-A-N>"); AssertSelectionsAdjustCaret( GetPoint(1, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(2, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // Select next occurrence above. ProcessNotation("<C-A-N>"); AssertSelectionsAdjustCaret( GetPoint(1, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(0, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(2, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // No more matches. var didHit = false; _vimBuffer.ErrorMessage += (_, args) => { Assert.Equal(Resources.VisualMode_NoMoreMatches, args.Message); didHit = true; }; ProcessNotation("<C-A-N>"); Assert.True(didHit); } } public sealed class VisualLineModeTest : MultiSelectionIntegrationTest { /// <summary> /// Test entering visual line mode /// </summary> [WpfFact] public void Enter() { Create("abc def", "ghi jkl", "mno pqr", "stu vwx", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(2, 4)); ProcessNotation("V"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); AssertSelections( GetPoint(0, 4).Position.GetSelectedSpan(-4, 5, false), // 'abc |def^M^J*' GetPoint(2, 4).Position.GetSelectedSpan(-4, 5, false)); // 'mno |pqr^M^J*' } /// <summary> /// Split selection into carets /// </summary> [WpfFact] public void SplitSelection() { Create(" abc def ghi", " jkl mno pqr", " stu vwx yz.", ""); SetCaretPoints(GetPoint(0, 4)); - ProcessNotation("Vjj<C-A-i>"); + ProcessNotation("Vjj<C-A-n>"); AssertCarets(GetPoint(0, 4), GetPoint(1, 4), GetPoint(2, 4)); } /// <summary> /// Test deleting lines /// </summary> [WpfFact] public void Delete() { Create("abc def", "ghi jkl", "mno pqr", "stu vwx", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(2, 4)); ProcessNotation("Vx"); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); AssertLines("ghi jkl", "stu vwx", ""); AssertCarets(GetPoint(0, 0), GetPoint(1, 0)); } } public sealed class VisualBlockModeTest : MultiSelectionIntegrationTest { [WpfFact] public void SplitSelection() { Create(" abc def ghi", " jkl mno pqr", " stu vwx yz.", ""); SetCaretPoints(GetPoint(0, 4)); - ProcessNotation("<C-V>jj<C-A-i>"); + ProcessNotation("<C-V>jj<C-A-n>"); AssertCarets(GetPoint(0, 4), GetPoint(1, 4), GetPoint(2, 4)); } } public sealed class SelectModeTest : MultiSelectionIntegrationTest { protected override void Create(params string[] lines) { base.Create(lines); _globalSettings.SelectModeOptions = SelectModeOptions.Mouse | SelectModeOptions.Keyboard | SelectModeOptions.Command; _globalSettings.KeyModelOptions = KeyModelOptions.StartSelection; _globalSettings.Selection = "exclusive"; } /// <summary> /// Test entering select mode /// </summary> [WpfFact] public void Enter() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 0), GetPoint(1, 0)); ProcessNotation("<S-Right>"); AssertSelections( GetPoint(0, 1).GetSelectedSpan(-1, 0, false), // 'a|' GetPoint(1, 1).GetSelectedSpan(-1, 0, false)); // 'j|' } /// <summary> /// Test replacing the selection /// </summary> [WpfFact] public void ReplaceSelection() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("gh<C-S-Right>xxx "); AssertLines("abc xxx ghi", "jkl xxx pqr", ""); AssertCarets(GetPoint(0, 8), GetPoint(1, 8)); } /// <summary> /// Test extending the selection forward /// </summary> [WpfFact] public void ExtendForward() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("gh<C-S-Right>"); AssertSelections( GetPoint(0, 8).GetSelectedSpan(-4, 0, false), // 'def |' GetPoint(1, 8).GetSelectedSpan(-4, 0, false)); // 'mno |' } /// <summary> /// Test add a selection on an adjacent line /// </summary> [WpfFact] public void AddSelection() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4)); ProcessNotation("gh<C-S-Right><C-A-Down>"); AssertSelections( GetPoint(0, 8).GetSelectedSpan(-4, 0, false), // 'def |' GetPoint(1, 8).GetSelectedSpan(-4, 0, false)); // 'mno |' } /// <summary> /// Test extending the selection backward /// </summary> [WpfFact] public void ExtendBackward() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 8), GetPoint(1, 8)); ProcessNotation("gh<C-S-Left>"); AssertSelections( GetPoint(0, 4).GetSelectedSpan(0, 4, true), // '|def ' GetPoint(1, 4).GetSelectedSpan(0, 4, true)); // '|mno ' } /// <summary> /// Test extending the selection through zero width /// </summary> [WpfFact] public void ExtendThroughZeroWidth() { Create("abc def ghi", "jkl mno pqr", ""); SetCaretPoints(GetPoint(0, 4), GetPoint(1, 4)); ProcessNotation("gh<C-S-Right><C-S-Left><C-S-Left>"); AssertSelections( GetPoint(0, 0).GetSelectedSpan(0, 4, true), // 'abc |' GetPoint(1, 0).GetSelectedSpan(0, 4, true)); // 'jkl |' } /// <summary> /// Using single-click should revert to a single caret /// </summary> [WpfFact] public void Click() { Create("abc def ghi jkl", "mno pqr stu vwx", ""); _textView.SetVisibleLineCount(2); SetCaretPoints(GetPoint(0, 0), GetPoint(1, 0)); _testableMouseDevice.Point = GetPoint(0, 5).Position; // 'e' in 'def' ProcessNotation("<LeftMouse><LeftRelease>"); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); AssertCarets(GetPoint(0, 5)); // d'|*'ef } /// <summary> /// Using double-click should revert to a single selection /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void SelectWord(bool isInclusive) { Create(isInclusive, "abc def ghi jkl", "mno pqr stu vwx", ""); _textView.SetVisibleLineCount(2); SetCaretPoints(GetPoint(0, 0), GetPoint(1, 0)); _testableMouseDevice.Point = GetPoint(0, 5).Position; // 'e' in 'def' ProcessNotation("<LeftMouse><LeftRelease><2-LeftMouse><LeftRelease>"); Assert.Equal(ModeKind.SelectCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'def|*' } /// <summary> /// Using ctrl-alt-double-click should add a word to the selection /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void AddWordToSelection(bool isInclusive) { Create(isInclusive, "abc def ghi jkl", "mno pqr stu vwx", ""); _textView.SetVisibleLineCount(2); // First double-click. _testableMouseDevice.Point = GetPoint(0, 5).Position; // 'e' in 'def' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease><C-A-2-LeftMouse><C-A-LeftRelease>"); Assert.Equal(ModeKind.SelectCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // Second double-click. _testableMouseDevice.Point = GetPoint(1, 9).Position; // 't' in 'stu' ProcessNotation("<C-A-LeftMouse><C-A-LeftRelease><C-A-2-LeftMouse><C-A-LeftRelease>"); Assert.Equal(ModeKind.SelectCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(0, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(1, 11).GetSelectedSpan(-3, 0, false)); // 'stu|*' or 'st|u*' } /// <summary> /// Adding the next occurrence of the primary selection should wrap /// </summary> [WpfTheory, InlineData(false), InlineData(true)] public void AddNextOccurrence(bool isInclusive) { Create(isInclusive, "abc def ghi", "abc def ghi", "abc def ghi", ""); SetCaretPoints(GetPoint(1, 5)); // Select word. ProcessNotation("<C-A-N>"); Assert.Equal(ModeKind.SelectCharacter, _vimBuffer.ModeKind); AssertSelectionsAdjustCaret( GetPoint(1, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // Select next occurrence below. ProcessNotation("<C-A-N>"); AssertSelectionsAdjustCaret( GetPoint(1, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(2, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // Select next occurrence above. ProcessNotation("<C-A-N>"); AssertSelectionsAdjustCaret( GetPoint(1, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(0, 7).GetSelectedSpan(-3, 0, false), // 'def|*' or 'de|f*' GetPoint(2, 7).GetSelectedSpan(-3, 0, false)); // 'def|*' or 'de|f*' // No more matches. var didHit = false; _vimBuffer.ErrorMessage += (_, args) => { Assert.Equal(Resources.VisualMode_NoMoreMatches, args.Message); didHit = true; }; ProcessNotation("<C-A-N>"); Assert.True(didHit); } } } }
VsVim/VsVim
7d6d478678e6c5a60ba8d3b1f2d972989cf48796
Review feedback (second pass)
diff --git a/Src/VimCore/CaretRegisterMap.fs b/Src/VimCore/CaretRegisterMap.fs index 97a3bc0..e39d79b 100644 --- a/Src/VimCore/CaretRegisterMap.fs +++ b/Src/VimCore/CaretRegisterMap.fs @@ -1,123 +1,123 @@ namespace Vim open System.Collections.Generic /// Mutable caret index object type internal CaretIndex() = let mutable _caretIndex = 0 member x.Value with get() = _caretIndex and set value = _caretIndex <- value /// Caret-aware IRegisterValueBacking implementation for the unnamed register. /// If there are multiple carets, each caret gets its own distinct value type internal CaretUnnamedRegisterValueBacking ( _caretIndex: CaretIndex, _unnamedRegister: Register ) = let _valueMap = Dictionary<int, RegisterValue>() member x.RegisterValue = if _caretIndex.Value = 0 then _unnamedRegister.RegisterValue else match _valueMap.TryGetValue(_caretIndex.Value) with | true, value -> value | _ -> _unnamedRegister.RegisterValue member x.SetRegisterValue value = if _caretIndex.Value = 0 then _unnamedRegister.RegisterValue <- value else _valueMap.[_caretIndex.Value] <- value interface IRegisterValueBacking with member x.RegisterValue with get () = x.RegisterValue and set value = x.SetRegisterValue value /// Caret-aware IRegisterValueBacking implementation for the clipboard /// register. If there are multiple carets, the primary caret uses the /// clipboard and each secondary caret uses that caret's unnamed register type internal CaretClipboardRegisterValueBacking ( _caretIndex: CaretIndex, _clipboardRegister: Register, _caretUnnamedRegister: Register ) = member x.RegisterValue = if _caretIndex.Value = 0 then _clipboardRegister.RegisterValue else _caretUnnamedRegister.RegisterValue member x.SetRegisterValue (value: RegisterValue) = if _caretIndex.Value = 0 then _clipboardRegister.RegisterValue <- value else _caretUnnamedRegister.RegisterValue <- value interface IRegisterValueBacking with member x.RegisterValue with get () = x.RegisterValue and set value = x.SetRegisterValue value -type CaretRegisterMap +type internal CaretRegisterMap ( _registerMap: IRegisterMap, _caretIndex: CaretIndex, _map: Map<RegisterName, Register> ) = member x.GetRegister name = match Map.tryFind name _map with | Some register -> register | None -> _registerMap.GetRegister name interface ICaretRegisterMap with member x.RegisterNames = _registerMap.RegisterNames member x.GetRegister name = x.GetRegister name member x.SetRegisterValue name value = let register = x.GetRegister name register.RegisterValue <- value member x.CaretIndex with get() = _caretIndex.Value and set value = _caretIndex.Value <- value new(registerMap: IRegisterMap) = let caretIndex = CaretIndex() let caretUnnamedRegister = let unnamedRegisterName = RegisterName.Unnamed let unnamedRegister = unnamedRegisterName |> registerMap.GetRegister let backing = CaretUnnamedRegisterValueBacking(caretIndex, unnamedRegister) :> IRegisterValueBacking Register(unnamedRegisterName, backing) let caretClipboardRegister = let clipboardRegisterName = RegisterName.SelectionAndDrop SelectionAndDropRegister.Star let clipboardRegister = clipboardRegisterName |> registerMap.GetRegister let backing = CaretClipboardRegisterValueBacking(caretIndex, clipboardRegister, caretUnnamedRegister) :> IRegisterValueBacking Register(clipboardRegisterName, backing) let map = seq { yield caretUnnamedRegister yield caretClipboardRegister } |> Seq.map (fun register -> register.Name, register) |> Map.ofSeq CaretRegisterMap(registerMap, caretIndex, map) diff --git a/Src/VimCore/CaretRegisterMap.fsi b/Src/VimCore/CaretRegisterMap.fsi index d23768f..70108fb 100644 --- a/Src/VimCore/CaretRegisterMap.fsi +++ b/Src/VimCore/CaretRegisterMap.fsi @@ -1,7 +1,7 @@ namespace Vim type internal CaretRegisterMap = - new: IRegisterMap -> CaretRegisterMap + new: registerMap: IRegisterMap -> CaretRegisterMap interface ICaretRegisterMap diff --git a/Src/VimCore/CoreInterfaces.fs b/Src/VimCore/CoreInterfaces.fs index 576ce71..2764e1e 100644 --- a/Src/VimCore/CoreInterfaces.fs +++ b/Src/VimCore/CoreInterfaces.fs @@ -1,652 +1,652 @@ #light namespace Vim open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Editor open Microsoft.VisualStudio.Text.Operations open Microsoft.VisualStudio.Text.Outlining open Microsoft.VisualStudio.Text.Classification open Microsoft.VisualStudio.Text.Tagging open Microsoft.VisualStudio.Utilities open System.Diagnostics open System.IO open System.Runtime.CompilerServices open System.Runtime.InteropServices open System.Threading.Tasks open Vim.Interpreter open System [<RequireQualifiedAccess>] [<NoComparison>] type CaretMovement = | Up | Right | Down | Left | Home | End | PageUp | PageDown | ControlUp | ControlRight | ControlDown | ControlLeft | ControlHome | ControlEnd with static member OfDirection direction = match direction with | Direction.Up -> CaretMovement.Up | Direction.Right -> CaretMovement.Right | Direction.Down -> CaretMovement.Down | Direction.Left -> CaretMovement.Left | _ -> raise (Contract.GetInvalidEnumException direction) type TextViewEventArgs(_textView: ITextView) = inherit System.EventArgs() member x.TextView = _textView type VimRcKind = | VimRc = 0 | VsVimRc = 1 type VimRcPath = { /// Which type of file was loaded VimRcKind: VimRcKind /// Full path to the file which the contents were loaded from FilePath: string } [<RequireQualifiedAccess>] type VimRcState = /// The VimRc file has not been processed at this point | None /// The load succeeded of the specified file. If there were any errors actually /// processing the load they will be captured in the string[] parameter. /// The load succeeded and the specified file was used | LoadSucceeded of VimRcPath: VimRcPath * Errors: string[] /// The load failed | LoadFailed [<RequireQualifiedAccess>] [<NoComparison>] type ChangeCharacterKind = /// Switch the characters to upper case | ToUpperCase /// Switch the characters to lower case | ToLowerCase /// Toggle the case of the characters | ToggleCase /// Rot13 encode the letters | Rot13 type IStatusUtil = /// Raised when there is a special status message that needs to be reported abstract OnStatus: string -> unit /// Raised when there is a long status message that needs to be reported abstract OnStatusLong: string seq -> unit /// Raised when there is an error message that needs to be reported abstract OnError: string -> unit /// Raised when there is a warning message that needs to be reported abstract OnWarning: string -> unit /// Abstracts away VsVim's interaction with the file system to facilitate testing type IFileSystem = /// Create the specified directory, returns true if it was actually created abstract CreateDirectory: path: string -> bool /// Get the directories to probe for RC files abstract GetVimRcDirectories: unit -> string[] /// Get the possible paths for a vimrc file in the order they should be /// considered abstract GetVimRcFilePaths: unit -> VimRcPath[] /// Attempt to read all of the lines from the given file abstract ReadAllLines: filePath: string -> string[] option /// Read the contents of the directory abstract ReadDirectoryContents: directoryPath: string -> string[] option abstract Read: filePath: string -> Stream option abstract Write: filePath: string -> stream: Stream -> bool /// Used for manipulating multiple selections type ISelectionUtil = /// Whether multi-selection is supported abstract IsMultiSelectionSupported: bool /// Get all the selected spans for the specified text view abstract GetSelectedSpans: unit -> SelectionSpan seq /// Set all the selected spans for the specified text view - abstract SetSelectedSpans: SelectionSpan seq -> unit + abstract SetSelectedSpans: selectedSpans: SelectionSpan seq -> unit /// Factory service for creating ISelectionUtil instances type ISelectionUtilFactory = /// Get the selection utility interface abstract GetSelectionUtil: textView: ITextView -> ISelectionUtil /// Service for creating ISelectionUtilFactory instances type ISelectionUtilFactoryService = /// Get the selection utility interface abstract GetSelectionUtilFactory: unit -> ISelectionUtilFactory /// Used to display a word completion list to the user type IWordCompletionSession = inherit IPropertyOwner /// Is the session dismissed abstract IsDismissed: bool /// The associated ITextView instance abstract TextView: ITextView /// Select the next word in the session abstract MoveNext: unit -> bool /// Select the previous word in the session. abstract MovePrevious: unit -> bool /// Commit the current session abstract Commit: unit -> unit /// Dismiss the completion session abstract Dismiss: unit -> unit /// Raised when the session is dismissed [<CLIEvent>] abstract Dismissed: IDelegateEvent<System.EventHandler> type WordCompletionSessionEventArgs(_wordCompletionSession: IWordCompletionSession) = inherit System.EventArgs() member x.WordCompletionSession = _wordCompletionSession /// Factory for creating a IWordCompletionSession instance. This type cannot be MEF imported /// but instead is available via IVimHost type IWordCompletionSessionFactory = /// Create a session with the given set of words abstract CreateWordCompletionSession: textView: ITextView -> wordSpan: SnapshotSpan -> words: string seq -> isForward: bool -> IWordCompletionSession option /// Factory service for creating IWordCompletionSession instances. This type is available as /// a MEF import type IWordCompletionSessionFactoryService = /// Create a session with the given set of words abstract CreateWordCompletionSession: textView: ITextView -> wordSpan: SnapshotSpan -> words: string seq -> isForward: bool -> IWordCompletionSession option /// Raised when the session is created [<CLIEvent>] abstract Created: IDelegateEvent<System.EventHandler<WordCompletionSessionEventArgs>> /// Wraps an ITextUndoTransaction so we can avoid all of the null checks type IUndoTransaction = /// Call when it completes abstract Complete: unit -> unit /// Cancels the transaction abstract Cancel: unit -> unit inherit System.IDisposable /// This is a IUndoTransaction that is specific to a given ITextView instance type ITextViewUndoTransaction = /// Adds an ITextUndoPrimitive which will reset the selection to the current /// state when redoing this edit abstract AddAfterTextBufferChangePrimitive: unit -> unit /// Adds an ITextUndoPrimitive which will reset the selection to the current /// state when undoing this change abstract AddBeforeTextBufferChangePrimitive: unit -> unit inherit IUndoTransaction /// Flags controlling the linked undo transaction behavior [<System.Flags>] type LinkedUndoTransactionFlags = | None = 0x0 | CanBeEmpty = 0x1 | EndsWithInsert = 0x2 /// Wraps a set of IUndoTransaction items such that they undo and redo as a single /// entity. type ILinkedUndoTransaction = /// Complete the linked operation abstract Complete: unit -> unit inherit System.IDisposable /// Wraps all of the undo and redo operations type IUndoRedoOperations = abstract TextUndoHistory: ITextUndoHistory option /// Is there an open linked undo transaction abstract InLinkedUndoTransaction: bool /// StatusUtil instance that is used to report errors abstract StatusUtil: IStatusUtil /// Close the IUndoRedoOperations and remove any attached event handlers abstract Close: unit -> unit /// Creates an Undo Transaction abstract CreateUndoTransaction: name: string -> IUndoTransaction /// Creates an Undo Transaction specific to the given ITextView. Use when operations /// like caret position need to be a part of the undo / redo stack abstract CreateTextViewUndoTransaction: name: string -> textView: ITextView -> ITextViewUndoTransaction /// Creates a linked undo transaction abstract CreateLinkedUndoTransaction: name: string -> ILinkedUndoTransaction /// Creates a linked undo transaction with flags abstract CreateLinkedUndoTransactionWithFlags: name: string -> flags: LinkedUndoTransactionFlags -> ILinkedUndoTransaction /// Wrap the passed in "action" inside an undo transaction. This is needed /// when making edits such as paste so that the cursor will move properly /// during an undo operation abstract EditWithUndoTransaction: name: string -> textView: ITextView -> action: (unit -> 'T) -> 'T /// Redo the last "count" operations abstract Redo: count:int -> unit /// Undo the last "count" operations abstract Undo: count:int -> unit /// Represents a set of changes to a contiguous region. [<RequireQualifiedAccess>] type TextChange = | DeleteLeft of Count: int | DeleteRight of Count: int | Insert of Text: string | Combination of Left: TextChange * Right: TextChange with /// Get the insert text resulting from the change if there is any member x.InsertText = let rec inner textChange (text: string) = match textChange with | Insert data -> text + data |> Some | DeleteLeft count -> if count > text.Length then None else text.Substring(0, text.Length - count) |> Some | DeleteRight _ -> None | Combination (left, right) -> match inner left text with | None -> None | Some text -> inner right text inner x StringUtil.Empty /// Get the last / most recent change in the TextChange tree member x.LastChange = match x with | DeleteLeft _ -> x | DeleteRight _ -> x | Insert _ -> x | Combination (_, right) -> right.LastChange member x.IsEmpty = match x with | Insert text -> StringUtil.IsNullOrEmpty text | DeleteLeft count -> count = 0 | DeleteRight count -> count = 0 | Combination (left, right) -> left.IsEmpty && right.IsEmpty member x.Reduce = match x with | Combination (left, right) -> match TextChange.ReduceCore left right with | Some reduced -> reduced | None -> x | _ -> x /// Merge two TextChange values together. The goal is to produce a the smallest TextChange /// value possible. This will return Some if a reduction is made and None if there is /// no possible reduction static member private ReduceCore left right = // This is called for combination merges. Some progress was made but it's possible further // progress could be made by reducing the specified values. If further progress can be made // keep it else keep at least the progress already made let tryReduceAgain left right = Some (TextChange.CreateReduced left right) // Insert can only merge with a previous insert operation. It can't // merge with any deletes that came before it let reduceInsert before (text: string) = match before with | Insert otherText -> Some (Insert (otherText + text)) | _ -> None // DeleteLeft can merge with deletes and previous insert operations. let reduceDeleteLeft before count = match before with | Insert otherText -> if count <= otherText.Length then let text = otherText.Substring(0, otherText.Length - count) Some (Insert text) else let count = count - otherText.Length Some (DeleteLeft count) | DeleteLeft beforeCount -> Some (DeleteLeft (count + beforeCount)) | _ -> None // Delete right can merge only with other DeleteRight operations let reduceDeleteRight before count = match before with | DeleteRight beforeCount -> Some (DeleteRight (beforeCount + count)) | _ -> None // The item on the left isn't a Combination item. So do simple merge semantics let simpleMerge () = match right with | Insert text -> reduceInsert left text | DeleteLeft count -> reduceDeleteLeft left count | DeleteRight count -> reduceDeleteRight left count | Combination (rightSubLeft, rightSubRight) -> // First just see if the combination itself can be reduced match TextChange.ReduceCore rightSubLeft rightSubRight with | Some reducedTextChange -> tryReduceAgain left reducedTextChange | None -> match TextChange.ReduceCore left rightSubLeft with | None -> None | Some reducedTextChange -> tryReduceAgain reducedTextChange rightSubRight // The item on the left is a Combination item. let complexMerge leftSubLeft leftSubRight = // First check if the left can be merged against itself. This can easily happen // for hand built trees match TextChange.ReduceCore leftSubLeft leftSubRight with | Some reducedTextChange -> tryReduceAgain reducedTextChange right | None -> // It can't be reduced. Still a change that the right can be reduced against // the subRight value match TextChange.ReduceCore leftSubRight right with | None -> None | Some reducedTextChange -> tryReduceAgain leftSubLeft reducedTextChange if left.IsEmpty then Some right elif right.IsEmpty then Some left else match left with | Insert _ -> simpleMerge () | DeleteLeft _ -> simpleMerge () | DeleteRight _ -> simpleMerge () | Combination (leftSubLeft, leftSubRight) -> complexMerge leftSubLeft leftSubRight static member Replace str = let left = str |> StringUtil.Length |> TextChange.DeleteLeft let right = TextChange.Insert str TextChange.Combination (left, right) static member CreateReduced left right = match TextChange.ReduceCore left right with | None -> Combination (left, right) | Some textChange -> textChange type TextChangeEventArgs(_textChange: TextChange) = inherit System.EventArgs() member x.TextChange = _textChange [<System.Flags>] type SearchOptions = | None = 0x0 /// Consider the "ignorecase" option when doing the search | ConsiderIgnoreCase = 0x1 /// Consider the "smartcase" option when doing the search | ConsiderSmartCase = 0x2 /// Whether to include the start point when doing the search | IncludeStartPoint = 0x4 /// ConsiderIgnoreCase ||| ConsiderSmartCase | Default = 0x3 /// Information about a search of a pattern type PatternData = { /// The Pattern to search for Pattern: string /// The direction in which the pattern was searched for Path: SearchPath } type PatternDataEventArgs(_patternData: PatternData) = inherit System.EventArgs() member x.PatternData = _patternData /// An incremental search can be augmented with a offset of characters or a line /// count. This is described in full in :help searh-offset' [<RequireQualifiedAccess>] [<StructuralEquality>] [<NoComparison>] [<DebuggerDisplay("{ToString(),nq}")>] type SearchOffsetData = | None | Line of Line: int | Start of Start: int | End of End: int | Search of PatternData: PatternData with static member private ParseCore (offset: string) = Contract.Requires (offset.Length > 0) let index = ref 0 let isForward = ref true let movePastPlusOrMinus () = if index.Value < offset.Length then match offset.[index.Value] with | '+' -> isForward := true index := index.Value + 1 true | '-' -> isForward := false index := index.Value + 1 true | _ -> false else false let parseNumber () = if movePastPlusOrMinus () && index.Value = offset.Length then // a single + or - counts as a value if it's not followed by // a number if isForward.Value then 1 else -1 else // parse out the digits after the value let mutable num = 0 let mutable isBad = index.Value >= offset.Length while index.Value < offset.Length do num <- num * 10 match CharUtil.GetDigitValue (offset.[index.Value]) with | Option.None -> isBad <- true index := offset.Length | Option.Some d -> num <- num + d index := index.Value + 1 if isBad then 0 elif isForward.Value then num else -num let parseLine () = let number = parseNumber () SearchOffsetData.Line number let parseEnd () = index := index.Value + 1 let number = parseNumber () SearchOffsetData.End number let parseStart () = index := index.Value + 1 let number = parseNumber () SearchOffsetData.Start number let parseSearch () = index := index.Value + 1 match StringUtil.CharAtOption index.Value offset with | Option.Some '/' -> let path = SearchPath.Forward let pattern = offset.Substring(index.Value + 1) SearchOffsetData.Search ({ Pattern = pattern; Path = path}) | Option.Some '?' -> let path = SearchPath.Backward let pattern = offset.Substring(index.Value + 1) SearchOffsetData.Search ({ Pattern = pattern; Path = path}) | _ -> SearchOffsetData.None if CharUtil.IsDigit (offset.[0]) then parseLine () else match offset.[0] with | '-' -> parseLine () | '+' -> parseLine () | 'e' -> parseEnd () | 's' -> parseStart () | 'b' -> parseStart () | ';' -> parseSearch () | _ -> SearchOffsetData.None static member Parse (offset: string) = if StringUtil.IsNullOrEmpty offset then SearchOffsetData.None else SearchOffsetData.ParseCore offset [<Sealed>] [<DebuggerDisplay("{ToString(),nq}")>] type SearchData ( _pattern: string, _offset: SearchOffsetData, _kind: SearchKind, _options: SearchOptions ) = new (pattern: string, path: SearchPath, isWrap: bool) = let kind = SearchKind.OfPathAndWrap path isWrap SearchData(pattern, SearchOffsetData.None, kind, SearchOptions.Default) new (pattern: string, path: SearchPath) = let kind = SearchKind.OfPathAndWrap path true SearchData(pattern, SearchOffsetData.None, kind, SearchOptions.Default) /// The pattern being searched for in the buffer member x.Pattern = _pattern /// The offset that is applied to the search member x.Offset = _offset member x.Kind = _kind member x.Options = _options member x.Path = x.Kind.Path /// The PatternData which was searched for. This does not include the pattern searched /// for in the offset member x.PatternData = { Pattern = x.Pattern; Path = x.Kind.Path } /// The SearchData which should be used for IVimData.LastSearchData if this search needs /// to update that value. It takes into account the search pattern in an offset string /// as specified in ':help //;' member x.LastSearchData = let path = x.Path let pattern = match x.Offset with | SearchOffsetData.Search patternData -> patternData.Pattern | _ -> x.Pattern SearchData(pattern, x.Offset, x.Kind, x.Options) member x.Equals(other: SearchData) = if obj.ReferenceEquals(other, null) then false else _pattern = other.Pattern && _offset = other.Offset && _kind = other.Kind && _options = other.Options override x.Equals(other: obj) = match other with | :? SearchData as otherSearchData -> x.Equals(otherSearchData) | _ -> false override x.GetHashCode() = _pattern.GetHashCode() override x.ToString() = x.Pattern static member op_Equality(this, other) = System.Collections.Generic.EqualityComparer<SearchData>.Default.Equals(this, other) static member op_Inequality(this, other) = not (System.Collections.Generic.EqualityComparer<SearchData>.Default.Equals(this, other)) /// Parse out a SearchData value given the specific pattern and SearchKind. The pattern should /// not include a beginning / or ?. That should be removed by this point static member Parse (pattern: string) (searchKind: SearchKind) searchOptions = let mutable index = -1 let mutable i = 1 let targetChar = if searchKind.IsAnyForward then '/' else '?' while i < pattern.Length do if pattern.[i] = targetChar && pattern.[i-1] <> '\\' then index <- i i <- pattern.Length else i <- i + 1 if index < 0 then SearchData(pattern, SearchOffsetData.None, searchKind, searchOptions) else let offset = SearchOffsetData.Parse (pattern.Substring(index + 1)) let pattern = pattern.Substring(0, index) diff --git a/Src/VimCore/MefComponents.fs b/Src/VimCore/MefComponents.fs index 47f63f1..423ec4d 100644 --- a/Src/VimCore/MefComponents.fs +++ b/Src/VimCore/MefComponents.fs @@ -48,532 +48,540 @@ type internal TrackingLineColumn member x.Line with get() = _line and set value = _line <- value member x.Offset = _offset member x.IsValid = Option.isSome _line member x.VirtualPoint = match _line with | None -> None | Some line -> Some (VirtualSnapshotPoint(line, _offset)) member x.Point = match x.VirtualPoint with | None -> None | Some point -> Some point.Position member x.Close () = _onClose x _line <- None _lastValidVersion <- None /// Update the internal tracking information based on the new ITextSnapshot member x.OnBufferChanged (e: TextContentChangedEventArgs) = match _line with | Some snapshotLine -> if e.AfterVersion <> snapshotLine.Snapshot.Version then x.AdjustForChange snapshotLine e | None -> x.CheckForUndo e /// The change occurred and we are in a valid state. Update our cached data against /// this change /// /// Note: This method occurs on a hot path, especially in macro playback, hence we /// take great care to avoid allocations on this path whenever possible member x.AdjustForChange (oldLine: ITextSnapshotLine) (e: TextContentChangedEventArgs) = let changes = e.Changes match _mode with | LineColumnTrackingMode.Default -> if x.IsLineDeletedByChange oldLine changes then // If this shouldn't survive a full line deletion and there is a deletion // then we are invalid x.MarkInvalid oldLine else x.AdjustForChangeCore oldLine e | LineColumnTrackingMode.LastEditPoint -> if x.IsLineDeletedByChange oldLine changes then _offset <- 0 let newSnapshot = e.After let number = min oldLine.LineNumber (newSnapshot.LineCount - 1) _line <- Some (newSnapshot.GetLineFromLineNumber number) | LineColumnTrackingMode.SurviveDeletes -> x.AdjustForChangeCore oldLine e member x.AdjustForChangeCore (oldLine: ITextSnapshotLine) (e: TextContentChangedEventArgs) = let newSnapshot = e.After let changes = e.Changes // Calculate the line number delta for this given change. All we care about here // is the line number. So changes line shortening the line don't matter for // us because the column position is fixed let mutable delta = 0 for change in changes do if change.LineCountDelta <> 0 && change.OldPosition <= oldLine.Start.Position then // The change occurred before our line and there is a delta. This is the // delta we need to apply to our line number delta <- delta + change.LineCountDelta let number = oldLine.LineNumber + delta if number >= 0 && number < newSnapshot.LineCount then _line <- Some (newSnapshot.GetLineFromLineNumber number) else x.MarkInvalid oldLine /// Is the specified line deleted by this change member x.IsLineDeletedByChange (snapshotLine: ITextSnapshotLine) (changes: INormalizedTextChangeCollection) = if changes.IncludesLineChanges then let span = snapshotLine.ExtentIncludingLineBreak.Span let mutable isDeleted = false for change in changes do if change.LineCountDelta < 0 && change.OldSpan.Contains span then isDeleted <- true isDeleted else false /// This line was deleted at some point in the past and hence we're invalid. If the /// current change is an Undo back to the last version where we were valid then we /// become valid again member x.CheckForUndo (e: TextContentChangedEventArgs) = Debug.Assert(not x.IsValid) match _lastValidVersion with | Some (version, lineNumber) -> let newSnapshot = e.After let newVersion = e.AfterVersion if newVersion.ReiteratedVersionNumber = version && lineNumber <= newSnapshot.LineCount then _line <- Some (newSnapshot.GetLineFromLineNumber(lineNumber)) _lastValidVersion <- None | None -> () /// For whatever reason this is now invalid. Store the last good information so we can /// recover during an undo operation member x.MarkInvalid (snapshotLine: ITextSnapshotLine) = _line <- None _lastValidVersion <- Some (snapshotLine.Snapshot.Version.ReiteratedVersionNumber, snapshotLine.LineNumber) override x.ToString() = match x.VirtualPoint with | Some point -> let line = SnapshotPointUtil.GetContainingLine point.Position sprintf "%d,%d - %s" line.LineNumber _offset (point.ToString()) | None -> "Invalid" interface ITrackingLineColumn with member x.TextBuffer = _textBuffer member x.TrackingMode = _mode member x.VirtualPoint = x.VirtualPoint member x.Point = x.Point member x.Column = match x.Point with Some p -> Some (SnapshotColumn(p)) | None -> None member x.VirtualColumn = match x.VirtualPoint with Some p -> Some (VirtualSnapshotColumn(p)) | None -> None member x.Close() = x.Close() /// Implementation of ITrackingVisualSpan which is used to track a VisualSpan across edits /// to the ITextBuffer [<RequireQualifiedAccess>] type internal TrackingVisualSpan = /// Tracks the origin SnapshotPoint of the character span, the number of lines it /// composes of and the length of the span on the last line | Character of TrackingLineColumn: ITrackingLineColumn * LineCount: int * LastLineMaxPositionCount: int /// Tracks the origin of the SnapshotLineRange and the number of lines it should comprise /// of | Line of TrackingLineColumn: ITrackingLineColumn * LineCount: int /// Tracks the origin of the block selection, it's tabstop by width by height | Block of TrackingLineColumn: ITrackingLineColumn * TabStop: int * Width: int * Height: int * EndOfLine: bool with member x.TrackingLineColumn = match x with | Character (trackingLineColumn, _, _) -> trackingLineColumn | Line (trackingLineColumn, _) -> trackingLineColumn | Block (trackingLineColumn, _, _, _, _) -> trackingLineColumn member x.TextBuffer = x.TrackingLineColumn.TextBuffer /// Calculate the VisualSpan against the current ITextSnapshot member x.VisualSpan = let snapshot = x.TextBuffer.CurrentSnapshot match x.TrackingLineColumn.Point with | None -> None | Some point -> match x with | Character (_, lineCount, lastLineMaxPositionCount) -> let characterSpan = CharacterSpan(point, lineCount, lastLineMaxPositionCount) VisualSpan.Character characterSpan | Line (_, count) -> let line = SnapshotPointUtil.GetContainingLine point SnapshotLineRangeUtil.CreateForLineAndMaxCount line count |> VisualSpan.Line | Block (_, tabStop, width, height, endOfLine) -> let virtualPoint = VirtualSnapshotPointUtil.OfPoint point let blockSpan = BlockSpan(virtualPoint, tabStop, width, height, endOfLine) VisualSpan.Block blockSpan |> Some member x.Close() = match x with | Character (trackingLineColumn, _, _) -> trackingLineColumn.Close() | Line (trackingLineColumn, _) -> trackingLineColumn.Close() | Block (trackingLineColumn, _, _, _, _) -> trackingLineColumn.Close() static member Create (bufferTrackingService: IBufferTrackingService) visualSpan = match visualSpan with | VisualSpan.Character characterSpan -> // Implemented by tracking the start point of the SnapshotSpan, the number of lines // in the span and the length of the final line let textBuffer = characterSpan.Snapshot.TextBuffer let trackingLineColumn = let line, offset = VirtualSnapshotPointUtil.GetLineAndOffset characterSpan.VirtualStart bufferTrackingService.CreateLineOffset textBuffer line.LineNumber offset LineColumnTrackingMode.Default TrackingVisualSpan.Character (trackingLineColumn, characterSpan.LineCount, characterSpan.LastLineMaxPositionCount) | VisualSpan.Line snapshotLineRange -> // Setup an ITrackingLineColumn at the 0 column of the first line. This actually may be doable // with an ITrackingPoint but for now sticking with an ITrackinglineColumn let textBuffer = snapshotLineRange.Snapshot.TextBuffer let trackingLineColumn = bufferTrackingService.CreateLineOffset textBuffer snapshotLineRange.StartLineNumber 0 LineColumnTrackingMode.Default TrackingVisualSpan.Line (trackingLineColumn, snapshotLineRange.Count) | VisualSpan.Block blockSpan -> // Setup an ITrackLineColumn at the top left of the block selection let trackingLineColumn = let textBuffer = blockSpan.TextBuffer let line, offset = VirtualSnapshotPointUtil.GetLineAndOffset blockSpan.VirtualStart.VirtualStartPoint bufferTrackingService.CreateLineOffset textBuffer line.LineNumber offset LineColumnTrackingMode.Default TrackingVisualSpan.Block (trackingLineColumn, blockSpan.TabStop, blockSpan.SpacesLength, blockSpan.Height, blockSpan.EndOfLine) interface ITrackingVisualSpan with member x.TextBuffer = x.TextBuffer member x.VisualSpan = x.VisualSpan member x.Close() = x.Close() type internal TrackingVisualSelection ( _trackingVisualSpan: ITrackingVisualSpan, _path: SearchPath, _column: int, _blockCaretLocation: BlockCaretLocation ) = member x.VisualSelection = match _trackingVisualSpan.VisualSpan with | None -> None | Some visualSpan -> let visualSelection = match visualSpan with | VisualSpan.Character span -> VisualSelection.Character (span, _path) | VisualSpan.Line lineRange -> VisualSelection.Line (lineRange, _path, _column) | VisualSpan.Block blockSpan -> VisualSelection.Block (blockSpan, _blockCaretLocation) Some visualSelection member x.CaretPoint = x.VisualSelection |> Option.map (fun visualSelection -> visualSelection.GetCaretPoint SelectionKind.Inclusive) /// Get the caret in the given VisualSpan member x.GetCaret visualSpan = x.VisualSelection |> Option.map (fun visualSelection -> visualSelection.GetCaretPoint SelectionKind.Inclusive) /// Create an ITrackingVisualSelection with the provided data static member Create (bufferTrackingService: IBufferTrackingService) (visualSelection: VisualSelection)= // Track the inclusive VisualSpan. Internally the VisualSelection type represents values as inclusive // ones. let trackingVisualSpan = bufferTrackingService.CreateVisualSpan visualSelection.VisualSpan let path, column, blockCaretLocation = match visualSelection with | VisualSelection.Character (_, path) -> path, 0, BlockCaretLocation.TopRight | VisualSelection.Line (_, path, column) -> path, column, BlockCaretLocation.TopRight | VisualSelection.Block (_, blockCaretLocation) -> SearchPath.Forward, 0, blockCaretLocation TrackingVisualSelection(trackingVisualSpan, path, column, blockCaretLocation) interface ITrackingVisualSelection with member x.CaretPoint = x.CaretPoint member x.TextBuffer = _trackingVisualSpan.TextBuffer member x.VisualSelection = x.VisualSelection member x.Close() = _trackingVisualSpan.Close() type internal TrackedData = { List: List<TrackingLineColumn> Observer: System.IDisposable } /// Service responsible for tracking various parts of an ITextBuffer which can't be replicated /// by simply using ITrackingSpan or ITrackingPoint. [<Export(typeof<IBufferTrackingService>)>] [<Sealed>] type internal BufferTrackingService() = static let _key = obj() member x.FindTrackedData (textBuffer: ITextBuffer) = PropertyCollectionUtil.GetValue<TrackedData> _key textBuffer.Properties /// Remove the TrackingLineColumn from the map. If it is the only remaining /// TrackingLineColumn assigned to the ITextBuffer, remove it from the map /// and unsubscribe from the Changed event member x.Remove (trackingLineColumn: TrackingLineColumn) = let textBuffer = trackingLineColumn.TextBuffer match x.FindTrackedData textBuffer with | Some trackedData -> trackedData.List.Remove trackingLineColumn |> ignore if trackedData.List.Count = 0 then trackedData.Observer.Dispose() textBuffer.Properties.RemoveProperty _key |> ignore | None -> () /// Add the TrackingLineColumn to the map. If this is the first item in the /// map then subscribe to the Changed event on the buffer member x.Add (trackingLineColumn: TrackingLineColumn) = let textBuffer = trackingLineColumn.TextBuffer let trackedData = match x.FindTrackedData textBuffer with | Some trackedData -> trackedData | None -> let observer = textBuffer.Changed |> Observable.subscribe x.OnBufferChanged let trackedData = { List = List<TrackingLineColumn>(); Observer = observer } textBuffer.Properties.AddProperty(_key, trackedData) trackedData trackedData.List.Add trackingLineColumn member x.OnBufferChanged (e: TextContentChangedEventArgs) = match x.FindTrackedData e.Before.TextBuffer with | Some trackedData -> trackedData.List |> Seq.iter (fun trackingLineColumn -> trackingLineColumn.OnBufferChanged e) | None -> () member x.CreateLineOffset (textBuffer: ITextBuffer) lineNumber offset mode = let trackingLineColumn = TrackingLineColumn(textBuffer, offset, mode, x.Remove) let textSnapshot = textBuffer.CurrentSnapshot let textLine = textSnapshot.GetLineFromLineNumber(lineNumber) trackingLineColumn.Line <- Some textLine x.Add trackingLineColumn trackingLineColumn member x.CreateColumn (column: SnapshotColumn) mode = let textBuffer = column.Snapshot.TextBuffer x.CreateLineOffset textBuffer column.LineNumber column.Offset mode member x.HasTrackingItems textBuffer = x.FindTrackedData textBuffer |> Option.isSome interface IBufferTrackingService with member x.CreateLineOffset textBuffer lineNumber offset mode = x.CreateLineOffset textBuffer lineNumber offset mode :> ITrackingLineColumn member x.CreateColumn column mode = x.CreateColumn column mode :> ITrackingLineColumn member x.CreateVisualSpan visualSpan = TrackingVisualSpan.Create x visualSpan :> ITrackingVisualSpan member x.CreateVisualSelection visualSelection = TrackingVisualSelection.Create x visualSelection :> ITrackingVisualSelection member x.HasTrackingItems textBuffer = x.HasTrackingItems textBuffer /// Component which monitors commands across IVimBuffer instances and /// updates the LastCommand value for repeat purposes [<Export(typeof<IVimBufferCreationListener>)>] type internal ChangeTracker [<ImportingConstructor>] ( _vim: IVim ) = let _vimData = _vim.VimData member x.OnVimBufferCreated (vimBuffer: IVimBuffer) = let handler = x.OnCommandRan vimBuffer.NormalMode.CommandRunner.CommandRan |> Event.add handler vimBuffer.VisualLineMode.CommandRunner.CommandRan |> Event.add handler vimBuffer.VisualBlockMode.CommandRunner.CommandRan |> Event.add handler vimBuffer.VisualCharacterMode.CommandRunner.CommandRan |> Event.add handler vimBuffer.InsertMode.CommandRan |> Event.add handler vimBuffer.ReplaceMode.CommandRan |> Event.add handler member x.OnCommandRan (args: CommandRunDataEventArgs) = let data = args.CommandRunData let command = data.CommandBinding if command.IsMovement || command.IsSpecial then // Movement and special commands don't participate in change tracking () elif command.IsRepeatable then let storedCommand = StoredCommand.OfCommand data.Command data.CommandBinding x.StoreCommand storedCommand else _vimData.LastCommand <- None /// Store the given StoredCommand as the last command executed in the IVimBuffer. Take into /// account linking with the previous command member x.StoreCommand currentCommand = match _vimData.LastCommand with | None -> // No last command so no linking to consider _vimData.LastCommand <- Some currentCommand | Some lastCommand -> let shouldLink = Util.IsFlagSet currentCommand.CommandFlags CommandFlags.LinkedWithPreviousCommand || Util.IsFlagSet lastCommand.CommandFlags CommandFlags.LinkedWithNextCommand if shouldLink then _vimData.LastCommand <- StoredCommand.LinkedCommand (lastCommand, currentCommand) |> Some else _vimData.LastCommand <- Some currentCommand interface IVimBufferCreationListener with member x.VimBufferCreated buffer = x.OnVimBufferCreated buffer /// Implements the safe dispatching interface which prevents application crashes for /// exceptions reaching the dispatcher loop [<Export(typeof<IProtectedOperations>)>] type internal ProtectedOperations = val _errorHandlers: List<Lazy<IExtensionErrorHandler>> [<ImportingConstructor>] new ([<ImportMany>] errorHandlers: Lazy<IExtensionErrorHandler> seq) = { _errorHandlers = errorHandlers |> GenericListUtil.OfSeq } new (errorHandler: IExtensionErrorHandler) = let l = Lazy<IExtensionErrorHandler>(fun _ -> errorHandler) let list = l |> Seq.singleton |> GenericListUtil.OfSeq { _errorHandlers = list } new () = { _errorHandlers = Seq.empty |> GenericListUtil.OfSeq } /// Produce a delegate that can safely execute the given action. If it throws an exception /// then make sure to alert the error handlers member private x.GetProtectedAction (action : Action): Action = let a () = try action.Invoke() with | e -> x.AlertAll e Action(a) member private x.GetProtectedEventHandler (eventHandler: EventHandler): EventHandler = let a sender e = try eventHandler.Invoke(sender, e) with | e -> x.AlertAll e EventHandler(a) /// Alert all of the IExtensionErrorHandlers that the given Exception occurred. Be careful to guard /// against them for Exceptions as we are still on the dispatcher loop here and exceptions would be /// fatal member x.AlertAll e = VimTrace.TraceError(e) for handler in x._errorHandlers do try handler.Value.HandleError(x, e) with | e -> Debug.Fail((sprintf "Error handler threw: %O" e)) interface IProtectedOperations with member x.GetProtectedAction action = x.GetProtectedAction action member x.GetProtectedEventHandler eventHandler = x.GetProtectedEventHandler eventHandler member x.Report ex = x.AlertAll ex [<Export(typeof<IVimSpecificServiceHost>)>] type internal VimSpecificServiceHost [<ImportingConstructor>] ( _vimHost: Lazy<IVimHost>, [<ImportMany>] _services: Lazy<IVimSpecificService> seq ) = member x.GetService<'T>(): 'T option = let vimHost = _vimHost.Value _services |> Seq.map (fun serviceLazy -> try let service = serviceLazy.Value if service.HostIdentifier = vimHost.HostIdentifier then match service :> obj with | :? 'T as t -> Some t | _ -> None else None with | _ -> None) |> SeqUtil.filterToSome |> SeqUtil.tryHeadOnly interface IVimSpecificServiceHost with member x.GetService<'T>() = x.GetService<'T>() [<Export(typeof<IWordCompletionSessionFactoryService>)>] type internal VimWordCompletionSessionFactoryService [<ImportingConstructor>] ( _vimSpecificServiceHost: IVimSpecificServiceHost ) = let _created = StandardEvent<WordCompletionSessionEventArgs>() member x.CreateWordCompletionSession textView wordSpan words isForward = match _vimSpecificServiceHost.GetService<IWordCompletionSessionFactory>() with | None -> None | Some factory -> match factory.CreateWordCompletionSession textView wordSpan words isForward with | None -> None | Some session -> _created.Trigger x (WordCompletionSessionEventArgs(session)) Some session interface IWordCompletionSessionFactoryService with member x.CreateWordCompletionSession textView wordSpan words isForward = x.CreateWordCompletionSession textView wordSpan words isForward [<CLIEvent>] member x.Created = _created.Publish type internal SingleSelectionUtil(_textView: ITextView) = member x.IsMultiSelectionSupported = false member x.GetSelectedSpans () = let caretPoint = _textView.Caret.Position.VirtualBufferPosition let anchorPoint = _textView.Selection.AnchorPoint let activePoint = _textView.Selection.ActivePoint seq { yield SelectionSpan(caretPoint, anchorPoint, activePoint) } member x.SetSelectedSpans (selectedSpans: SelectionSpan seq) = let selectedSpan = Seq.head selectedSpans _textView.Caret.MoveTo(selectedSpan.CaretPoint) |> ignore if selectedSpan.Length <> 0 then _textView.Selection.Select(selectedSpan.AnchorPoint, selectedSpan.ActivePoint) interface ISelectionUtil with member x.IsMultiSelectionSupported = x.IsMultiSelectionSupported member x.GetSelectedSpans() = x.GetSelectedSpans() member x.SetSelectedSpans selectedSpans = x.SetSelectedSpans selectedSpans type internal SingleSelectionUtilFactory() = - member x.GetSelectionUtil textView = - SingleSelectionUtil(textView) :> ISelectionUtil + static let s_key = new obj() + + member x.GetSelectionUtil (textView: ITextView) = + let propertyCollection = textView.Properties + propertyCollection.GetOrCreateSingletonProperty(s_key, + fun () -> SingleSelectionUtil(textView) :> ISelectionUtil) interface ISelectionUtilFactory with member x.GetSelectionUtil textView = x.GetSelectionUtil textView [<Export(typeof<ISelectionUtilFactoryService>)>] type internal SelectionUtilService [<ImportingConstructor>] ( _vimSpecificServiceHost: IVimSpecificServiceHost ) = + static let s_singleSelectionUtilFactory = + SingleSelectionUtilFactory() + :> ISelectionUtilFactory + member x.GetSelectionUtilFactory () = match _vimSpecificServiceHost.GetService<ISelectionUtilFactory>() with | Some selectionUtilFactory -> selectionUtilFactory - | None -> SingleSelectionUtilFactory() :> ISelectionUtilFactory + | None -> s_singleSelectionUtilFactory interface ISelectionUtilFactoryService with member x.GetSelectionUtilFactory () = x.GetSelectionUtilFactory() diff --git a/Src/VimCore/MefInterfaces.fs b/Src/VimCore/MefInterfaces.fs index a2c0fe7..331fe18 100644 --- a/Src/VimCore/MefInterfaces.fs +++ b/Src/VimCore/MefInterfaces.fs @@ -26,667 +26,667 @@ type IDisplayWindowBroker = /// Dismiss any completion windows on the given ITextView abstract DismissDisplayWindows: unit -> unit type IDisplayWindowBrokerFactoryService = /// Get the display broker for the provided ITextView abstract GetDisplayWindowBroker: textView: ITextView -> IDisplayWindowBroker /// What type of tracking are we doing [<RequireQualifiedAccess>] [<NoComparison>] [<NoEquality>] type LineColumnTrackingMode = /// By default a 1TrackingLineColumn will be deleted if the line it /// tracks is deleted | Default /// ITrackingLineColumn should survive the deletion of it's line /// and just treat it as a delta adjustment | SurviveDeletes /// Same as Survives delete but it resets the column to 0 in this /// case | LastEditPoint /// Tracks a line number and column across edits to the ITextBuffer. This auto tracks /// and will return information against the current ITextSnapshot for the /// ITextBuffer type ITrackingLineColumn = /// ITextBuffer this ITrackingLineColumn is tracking against abstract TextBuffer: ITextBuffer /// Returns the LineColumnTrackingMode for this instance abstract TrackingMode: LineColumnTrackingMode /// Get the point as it relates to current Snapshot. abstract Point: SnapshotPoint option /// Get the point as a VirtualSnapshot point on the current ITextSnapshot abstract VirtualPoint: VirtualSnapshotPoint option /// Get the column as it relates to current Snapshot. abstract Column: SnapshotColumn option /// Get the column as a VirtualSnapshotColumn point on the current ITextSnapshot abstract VirtualColumn: VirtualSnapshotColumn option /// Needs to be called when you are done with the ITrackingLineColumn abstract Close: unit -> unit /// Tracks a VisualSpan across edits to the underlying ITextBuffer. type ITrackingVisualSpan = /// The associated ITextBuffer instance abstract TextBuffer: ITextBuffer /// Get the VisualSpan as it relates to the current ITextSnapshot abstract VisualSpan: VisualSpan option /// Needs to be called when the consumer is finished with the ITrackingVisualSpan abstract Close: unit -> unit /// Tracks a Visual Selection across edits to the underlying ITextBuffer. This tracks both /// the selection area and the caret within the selection type ITrackingVisualSelection = /// The SnapshotPoint for the caret within the current ITextSnapshot abstract CaretPoint: SnapshotPoint option /// The associated ITextBuffer instance abstract TextBuffer: ITextBuffer /// Get the Visual Selection as it relates to the current ITextSnapshot abstract VisualSelection: VisualSelection option /// Needs to be called when the consumer is finished with the ITrackingVisualSpan abstract Close: unit -> unit type IBufferTrackingService = /// Create an ITrackingLineColumn at the given position in the buffer. abstract CreateLineOffset: textBuffer: ITextBuffer -> lineNumber: int -> offset: int -> mode: LineColumnTrackingMode -> ITrackingLineColumn /// Create an ITrackingLineColumn at the given SnaphsotColumn abstract CreateColumn: column: SnapshotColumn -> mode: LineColumnTrackingMode -> ITrackingLineColumn /// Create an ITrackingVisualSpan for the given VisualSpan abstract CreateVisualSpan: visualSpan: VisualSpan -> ITrackingVisualSpan /// Create an ITrackingVisualSelection for the given Visual Selection abstract CreateVisualSelection: visualSelection: VisualSelection -> ITrackingVisualSelection /// Does the given ITextBuffer have any out standing tracking instances abstract HasTrackingItems: textBuffer: ITextBuffer -> bool type IVimBufferCreationListener = /// Called whenever an IVimBuffer is created abstract VimBufferCreated: vimBuffer: IVimBuffer -> unit /// Supports the creation and deletion of folds within a ITextBuffer. Most components /// should talk to IFoldManager directly type IFoldData = /// Associated ITextBuffer the data is over abstract TextBuffer: ITextBuffer /// Gets snapshot spans for all of the currently existing folds. This will /// only return the folds explicitly created by vim. It won't return any /// collapsed regions in the ITextView abstract Folds: SnapshotSpan seq /// Create a fold for the given line range abstract CreateFold: SnapshotLineRange -> unit /// Delete a fold which crosses the given SnapshotPoint. Returns false if /// there was no fold to be deleted abstract DeleteFold: SnapshotPoint -> bool /// Delete all of the folds which intersect the given SnapshotSpan abstract DeleteAllFolds: SnapshotSpan -> unit /// Raised when the collection of folds are updated for any reason [<CLIEvent>] abstract FoldsUpdated: IDelegateEvent<System.EventHandler> /// Supports the creation and deletion of folds within a ITextBuffer /// /// TODO: This should become a merger between folds and outlining regions in /// an ITextBuffer / ITextView type IFoldManager = /// Associated ITextView abstract TextView: ITextView /// Create a fold for the given line range. The fold will be created in a closed state. abstract CreateFold: range: SnapshotLineRange -> unit /// Close 'count' fold values under the given SnapshotPoint abstract CloseFold: point: SnapshotPoint -> count: int -> unit /// Close all folds which intersect the given SnapshotSpan abstract CloseAllFolds: span: SnapshotSpan -> unit /// Delete a fold which crosses the given SnapshotPoint. Returns false if /// there was no fold to be deleted abstract DeleteFold: point: SnapshotPoint -> unit /// Delete all of the folds which intersect the SnapshotSpan abstract DeleteAllFolds: span: SnapshotSpan -> unit /// Toggle fold under the given SnapshotPoint abstract ToggleFold: point: SnapshotPoint -> count: int -> unit /// Toggle all folds under the given SnapshotPoint abstract ToggleAllFolds: span: SnapshotSpan -> unit /// Open 'count' folds under the given SnapshotPoint abstract OpenFold: point: SnapshotPoint -> count: int -> unit /// Open all folds which intersect the given SnapshotSpan abstract OpenAllFolds: span: SnapshotSpan -> unit /// Supports the get and creation of IFoldManager for a given ITextBuffer type IFoldManagerFactory = /// Get the IFoldData for this ITextBuffer abstract GetFoldData: textBuffer: ITextBuffer -> IFoldData /// Get the IFoldManager for this ITextView. abstract GetFoldManager: textView: ITextView -> IFoldManager /// Used because the actual Point class is in WPF which isn't available at this layer. [<Struct>] type VimPoint = { X: double Y: double } /// Abstract representation of the mouse type IMouseDevice = /// Is the left button pressed abstract IsLeftButtonPressed: bool /// Is the right button pressed abstract IsRightButtonPressed: bool /// Get the position of the mouse position within the ITextView abstract GetPosition: textView: ITextView -> VimPoint option /// Is the given ITextView in the middle fo a drag operation? abstract InDragOperation: textView: ITextView -> bool /// Abstract representation of the keyboard type IKeyboardDevice = /// Is the given key pressed abstract IsArrowKeyDown: bool /// The modifiers currently pressed on the keyboard abstract KeyModifiers: VimKeyModifiers /// Tracks changes to the associated ITextView type ILineChangeTracker = /// Swap the most recently changed line with its saved copy abstract Swap: unit -> bool /// Manages the ILineChangeTracker instances type ILineChangeTrackerFactory = /// Get the ILineChangeTracker associated with the given vim buffer information abstract GetLineChangeTracker: vimBufferData: IVimBufferData -> ILineChangeTracker /// Provides access to the system clipboard type IClipboardDevice = /// Whether to report errors that occur when using the clipboard abstract ReportErrors: bool with get, set /// The text contents of the clipboard device abstract Text: string with get, set [<RequireQualifiedAccess>] [<NoComparison>] [<NoEquality>] type Result = | Succeeded | Failed of Error: string [<Flags>] type ViewFlags = | None = 0 /// Ensure the context point is visible in the ITextView | Visible = 0x01 /// If the context point is inside a collapsed region then it needs to be exapnded | TextExpanded = 0x02 /// Using the context point as a reference ensure the scroll respects the 'scrolloff' /// setting | ScrollOffset = 0x04 /// Possibly move the caret to account for the 'virtualedit' setting | VirtualEdit = 0x08 /// Standard flags: /// Visible ||| TextExpanded ||| ScrollOffset | Standard = 0x07 /// All flags /// Visible ||| TextExpanded ||| ScrollOffset ||| VirtualEdit | All = 0x0f [<RequireQualifiedAccess>] [<NoComparison>] type RegisterOperation = | Yank | Delete /// Force the operation to be treated like a big delete even if it's a small one. | BigDelete /// This class abstracts out the operations that are common to normal, visual and /// command mode. It usually contains common edit and movement operations and very /// rarely will deal with caret operations. That is the responsibility of the /// caller type ICommonOperations = /// Run the beep operation abstract Beep: unit -> unit /// Associated IEditorOperations abstract EditorOperations: IEditorOperations /// Associated IEditorOptions abstract EditorOptions: IEditorOptions /// Whether multi-selection is supported abstract IsMultiSelectionSupported: bool /// The primary selected span abstract PrimarySelectedSpan: SelectionSpan /// The current selected spans abstract SelectedSpans: SelectionSpan seq /// The snapshot point in the buffer under the mouse cursor abstract MousePoint: VirtualSnapshotPoint option /// Associated ITextView abstract TextView: ITextView /// Associated VimBufferData instance abstract VimBufferData: IVimBufferData /// Add a new caret at the specified point abstract AddCaretAtPoint: point: VirtualSnapshotPoint -> unit /// Add a new caret at the mouse point abstract AddCaretAtMousePoint: unit -> unit /// Add a caret or selection on an adjacent line in the specified direction abstract AddCaretOrSelectionOnAdjacentLine: direction: Direction -> unit /// Adjust the ITextView scrolling to account for the 'scrolloff' setting after a move operation /// completes abstract AdjustTextViewForScrollOffset: unit -> unit /// This is the same function as AdjustTextViewForScrollOffsetAtPoint except that it moves the caret /// not the view port. Make the caret consistent with the setting not the display abstract AdjustCaretForScrollOffset: unit -> unit /// Adjust the caret if it is past the end of line and 'virtualedit=onemore' is not set abstract AdjustCaretForVirtualEdit: unit -> unit abstract member CloseWindowUnlessDirty: unit -> unit /// Create a possibly LineWise register value with the specified string value at the given /// point. This is factored out here because a LineWise value in vim should always /// end with a new line but we can't always guarantee the text we are working with /// contains a new line. This normalizes out the process needed to make this correct /// while respecting the settings of the ITextBuffer abstract CreateRegisterValue: point: SnapshotPoint -> stringData: StringData -> operationKind: OperationKind -> RegisterValue /// Delete at least count lines from the buffer starting from the provided line. The /// operation will fail if there aren't at least 'maxCount' lines in the buffer from /// the start point. /// /// This operation is performed against the visual buffer. abstract DeleteLines: startLine: ITextSnapshotLine -> maxCount: int -> registerName: RegisterName option -> unit /// Perform the specified action asynchronously using the scheduler abstract DoActionAsync: action: (unit -> unit) -> unit /// Perform the specified action when the text view is ready abstract DoActionWhenReady: action: (unit -> unit) -> unit /// Ensure the view properties are met at the caret abstract EnsureAtCaret: viewFlags: ViewFlags -> unit /// Ensure the view properties are met at the point abstract EnsureAtPoint: point: SnapshotPoint -> viewFlags: ViewFlags -> unit /// Filter the specified line range through the specified command abstract FilterLines: SnapshotLineRange -> command: string -> unit /// Format the specified line range abstract FormatCodeLines: SnapshotLineRange -> unit /// Format the specified line range abstract FormatTextLines: SnapshotLineRange -> preserveCaretPosition: bool -> unit /// Forward the specified action to the focused window abstract ForwardToFocusedWindow: action: (ICommonOperations -> unit) -> unit /// Get the new line text which should be used for new lines at the given SnapshotPoint abstract GetNewLineText: SnapshotPoint -> string /// Get the register to use based on the name provided to the operation. abstract GetRegister: name: RegisterName option -> Register /// Get the indentation for a newly created ITextSnasphotLine. The context line is /// is provided to calculate the indentation off of /// /// Warning: Calling this API can cause the buffer to be edited. Asking certain /// editor implementations about the indentation, in particular Razor, can cause /// an edit to occur. /// /// Issue #946 abstract GetNewLineIndent: contextLine: ITextSnapshotLine -> newLine: ITextSnapshotLine -> int option /// Get the standard ReplaceData for the given SnapshotPoint abstract GetReplaceData: point: SnapshotPoint -> VimRegexReplaceData /// Get the current number of spaces to caret we are maintaining abstract GetSpacesToCaret: unit -> int /// Get the number of spaces (when tabs are expanded) that is necessary to get to the /// specified point on it's line abstract GetSpacesToPoint: point: SnapshotPoint -> int /// Get the point that visually corresponds to the specified column on its line abstract GetColumnForSpacesOrEnd: contextLine: ITextSnapshotLine -> spaces: int -> SnapshotColumn /// Get the number of spaces (when tabs are expanded) that is necessary to get to the /// specified virtual point on it's line abstract GetSpacesToVirtualColumn: column: VirtualSnapshotColumn -> int /// Get the virtual point that visually corresponds to the specified column on its line abstract GetVirtualColumnForSpaces: contextLine: ITextSnapshotLine -> spaces: int -> VirtualSnapshotColumn /// Attempt to GoToDefinition on the current state of the buffer. If this operation fails, an error message will /// be generated as appropriate abstract GoToDefinition: unit -> Result /// Go to the file named in the word under the cursor abstract GoToFile: unit -> unit /// Go to the file name specified as a paramter abstract GoToFile: string -> unit /// Go to the file named in the word under the cursor in a new window abstract GoToFileInNewWindow: unit -> unit /// Go to the file name specified as a paramter in a new window abstract GoToFileInNewWindow: string -> unit /// Go to the local declaration of the word under the cursor abstract GoToLocalDeclaration: unit -> unit /// Go to the global declaration of the word under the cursor abstract GoToGlobalDeclaration: unit -> unit /// Go to the "count" next tab window in the specified direction. This will wrap /// around abstract GoToNextTab: path: SearchPath -> count: int -> unit /// Go the nth tab. This uses vim's method of numbering tabs which is a 1 based list. Both /// 0 and 1 can be used to access the first tab abstract GoToTab: int -> unit /// Using the specified base folder, go to the tag specified by ident abstract GoToTagInNewWindow: folder: string -> ident: string -> Result /// Convert any virtual spaces into real spaces / tabs based on the current settings. The caret /// will be positioned at the end of that change abstract FillInVirtualSpace: unit -> unit /// Joins the lines in the range abstract Join: SnapshotLineRange -> JoinKind -> unit /// Load a file into a new window, optionally moving the caret to the first /// non-blank on a specific line or to a specific line and column abstract LoadFileIntoNewWindow: file: string -> lineNumber: int option -> columnNumber: int option -> Result /// Move the caret in the specified direction abstract MoveCaret: caretMovement: CaretMovement -> bool /// Move the caret in the specified direction with an arrow key abstract MoveCaretWithArrow: caretMovement: CaretMovement -> bool /// Move the caret to a given point on the screen and ensure the view has the specified /// properties at that point abstract MoveCaretToColumn: column: SnapshotColumn -> viewFlags: ViewFlags -> unit /// Move the caret to a given virtual point on the screen and ensure the view has the specified /// properties at that point abstract MoveCaretToVirtualColumn: column: VirtualSnapshotColumn -> viewFlags: ViewFlags -> unit /// Move the caret to a given point on the screen and ensure the view has the specified /// properties at that point abstract MoveCaretToPoint: point: SnapshotPoint -> viewFlags: ViewFlags -> unit /// Move the caret to a given virtual point on the screen and ensure the view has the specified /// properties at that point abstract MoveCaretToVirtualPoint: point: VirtualSnapshotPoint -> viewFlags: ViewFlags -> unit /// Move the caret to the MotionResult value abstract MoveCaretToMotionResult: motionResult: MotionResult -> unit /// Navigate to the given point which may occur in any ITextBuffer. This will not update the /// jump list abstract NavigateToPoint: VirtualSnapshotPoint -> bool /// Normalize the spaces and tabs in the string abstract NormalizeBlanks: text: string -> spacesToColumn: int -> string /// Normalize the spaces and tabs in the string at the given column in the buffer abstract NormalizeBlanksAtColumn: text: string -> column: SnapshotColumn -> string /// Normalize the spaces and tabs in the string for a new tabstop abstract NormalizeBlanksForNewTabStop: text: string -> spacesToColumn: int -> tabStop: int -> string /// Normalize the set of spaces and tabs into spaces abstract NormalizeBlanksToSpaces: text: string -> spacesToColumn: int -> string /// Display a status message and fit it to the size of the window abstract OnStatusFitToWindow: message: string -> unit /// Open link under caret abstract OpenLinkUnderCaret: unit -> Result /// Put the specified StringData at the given point. abstract Put: SnapshotPoint -> StringData -> OperationKind -> unit /// Raise the error / warning messages for the given SearchResult abstract RaiseSearchResultMessage: SearchResult -> unit /// Record last change start and end positions abstract RecordLastChange: oldSpan: SnapshotSpan -> newSpan: SnapshotSpan -> unit /// Record last yank start and end positions abstract RecordLastYank: span: SnapshotSpan -> unit /// Redo the buffer changes "count" times abstract Redo: count:int -> unit /// Restore spaces to caret, or move to start of line if 'startofline' is set abstract RestoreSpacesToCaret: spacesToCaret: int -> useStartOfLine: bool -> unit /// Run the specified action for all selections abstract RunForAllSelections: action: (unit -> CommandResult) -> CommandResult /// Scrolls the number of lines given and keeps the caret in the view abstract ScrollLines: ScrollDirection -> count:int -> unit /// Set the current selected spans - abstract SetSelectedSpans: SelectionSpan seq -> unit + abstract SetSelectedSpans: selectedSpans: SelectionSpan seq -> unit /// Update the register with the specified value abstract SetRegisterValue: name: RegisterName option -> operation: RegisterOperation -> value: RegisterValue -> unit /// Shift the block of lines to the left by shiftwidth * 'multiplier' abstract ShiftLineBlockLeft: SnapshotSpan seq -> multiplier: int -> unit /// Shift the block of lines to the right by shiftwidth * 'multiplier' abstract ShiftLineBlockRight: SnapshotSpan seq -> multiplier: int -> unit /// Shift the given line range left by shiftwidth * 'multiplier' abstract ShiftLineRangeLeft: SnapshotLineRange -> multiplier: int -> unit /// Shift the given line range right by shiftwidth * 'multiplier' abstract ShiftLineRangeRight: SnapshotLineRange -> multiplier: int -> unit /// Sort the given line range abstract SortLines: SnapshotLineRange -> reverseOrder: bool -> SortFlags -> pattern: string option -> unit /// Substitute Command implementation abstract Substitute: pattern: string -> replace: string -> SnapshotLineRange -> flags: SubstituteFlags -> unit /// Toggle the use of typing language characters abstract ToggleLanguage: isForInsert: bool -> unit /// Map the specified point with negative tracking to the current snapshot abstract MapPointNegativeToCurrentSnapshot: point: SnapshotPoint -> SnapshotPoint /// Map the specified point with positive tracking to the current snapshot abstract MapPointPositiveToCurrentSnapshot: point: SnapshotPoint -> SnapshotPoint /// Map the specified virtual point to the current snapshot abstract MapCaretPointToCurrentSnapshot: point: VirtualSnapshotPoint -> VirtualSnapshotPoint /// Map the specified point with positive tracking to the current snapshot abstract MapSelectedSpanToCurrentSnapshot: point: SelectionSpan -> SelectionSpan /// Undo the buffer changes "count" times abstract Undo: count: int -> unit /// Raised when the selected spans are set [<CLIEvent>] abstract SelectedSpansSet: IDelegateEvent<System.EventHandler<System.EventArgs>> /// Factory for getting ICommonOperations instances type ICommonOperationsFactory = /// Get the ICommonOperations instance for this IVimBuffer abstract GetCommonOperations: IVimBufferData -> ICommonOperations /// This interface is used to prevent the transition from insert to visual mode /// when a selection occurs. In the majority case a selection of text should result /// in a transition to visual mode. In some cases though, C# event handlers being /// the most notable, the best experience is for the buffer to remain in insert /// mode type IVisualModeSelectionOverride = /// Is insert mode preferred for the current state of the buffer abstract IsInsertModePreferred: textView: ITextView -> bool /// What source should the synchronizer use as the original settings? The values /// in the selected source will be copied over the other settings [<RequireQualifiedAccess>] type SettingSyncSource = | Editor | Vim [<Struct>] type SettingSyncData = { EditorOptionKey: string GetEditorValue: IEditorOptions -> SettingValue option VimSettingName: string GetVimSettingValue: IVimBuffer -> obj IsLocal: bool } with member x.IsWindow = not x.IsLocal member x.GetSettings vimBuffer = SettingSyncData.GetSettingsCore vimBuffer x.IsLocal static member private GetSettingsCore (vimBuffer: IVimBuffer) isLocal = if isLocal then vimBuffer.LocalSettings :> IVimSettings else vimBuffer.WindowSettings :> IVimSettings static member GetBoolValueFunc (editorOptionKey: EditorOptionKey<bool>) = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions editorOptionKey with | None -> None | Some value -> SettingValue.Toggle value |> Some) static member GetNumberValueFunc (editorOptionKey: EditorOptionKey<int>) = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions editorOptionKey with | None -> None | Some value -> SettingValue.Number value |> Some) static member GetStringValue (editorOptionKey: EditorOptionKey<string>) = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions editorOptionKey with | None -> None | Some value -> SettingValue.String value |> Some) static member GetSettingValueFunc name isLocal = (fun (vimBuffer: IVimBuffer) -> let settings = SettingSyncData.GetSettingsCore vimBuffer isLocal match settings.GetSetting name with | None -> null | Some setting -> match setting.Value with | SettingValue.String value -> value :> obj | SettingValue.Toggle value -> box value | SettingValue.Number value -> box value) static member Create (key: EditorOptionKey<'T>) (settingName: string) (isLocal: bool) (convertEditorValue: Func<'T, SettingValue>) (convertSettingValue: Func<SettingValue, obj>) = { EditorOptionKey = key.Name GetEditorValue = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions key with | None -> None | Some value -> convertEditorValue.Invoke value |> Some) VimSettingName = settingName GetVimSettingValue = (fun vimBuffer -> let settings = SettingSyncData.GetSettingsCore vimBuffer isLocal match settings.GetSetting settingName with | None -> null | Some setting -> convertSettingValue.Invoke setting.Value) IsLocal = isLocal } /// This interface is used to synchronize settings between vim settings and the /// editor settings type IEditorToSettingsSynchronizer = /// Begin the synchronization between the editor and vim settings. This will /// start by overwriting the editor settings with the current local ones /// /// This method can be called multiple times for the same IVimBuffer and it /// will only synchronize once abstract StartSynchronizing: vimBuffer: IVimBuffer -> source: SettingSyncSource -> unit abstract SyncSetting: data: SettingSyncData -> unit /// There are some VsVim services which are only valid in specific host environments. These /// services will implement and export this interface. At runtime the identifier can be /// compared to the IVimHost.Identifier to see if it's valid type IVimSpecificService = abstract HostIdentifier: string /// This will look for an export of <see cref="IVimSpecificService"\> that is convertible to /// 'T and return it type IVimSpecificServiceHost = abstract GetService: unit -> 'T option diff --git a/Src/VimSpecific/Implementation/MultiSelection/MultiSelectionUtilFactory.cs b/Src/VimSpecific/Implementation/MultiSelection/MultiSelectionUtilFactory.cs index 7994bd1..c8df101 100644 --- a/Src/VimSpecific/Implementation/MultiSelection/MultiSelectionUtilFactory.cs +++ b/Src/VimSpecific/Implementation/MultiSelection/MultiSelectionUtilFactory.cs @@ -1,103 +1,107 @@ #if VS_SPECIFIC_2015 || VS_SPECIFIC_2017 #else using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using Vim; using Vim.VisualStudio.Specific; namespace Vim.Specific.Implementation.MultiSelection { [Export(typeof(ISelectionUtilFactory))] [Export(typeof(IVimSpecificService))] internal sealed class MultiSelectionUtilFactory : VimSpecificService, ISelectionUtilFactory { - private class MultiSelectionUtil : ISelectionUtil + private static readonly object s_key = new object(); + + private sealed class MultiSelectionUtil : ISelectionUtil { private readonly ITextView _textView; public MultiSelectionUtil(ITextView textView) { _textView = textView; } bool ISelectionUtil.IsMultiSelectionSupported => true; IEnumerable<SelectionSpan> ISelectionUtil.GetSelectedSpans() { if (_textView.Selection.Mode == TextSelectionMode.Box) { var caretPoint = _textView.Caret.Position.VirtualBufferPosition; var anchorPoint = _textView.Selection.AnchorPoint; var activePoint = _textView.Selection.ActivePoint; return new[] { new SelectionSpan(caretPoint, anchorPoint, activePoint) }; } var broker = _textView.GetMultiSelectionBroker(); var primarySelection = broker.PrimarySelection; var secondarySelections = broker.AllSelections .Where(span => span != primarySelection) .Select(selection => GetSelectedSpan(selection)); return new[] { GetSelectedSpan(primarySelection) }.Concat(secondarySelections); } void ISelectionUtil.SetSelectedSpans(IEnumerable<SelectionSpan> selectedSpans) { SetSelectedSpansCore(selectedSpans.ToArray()); } private void SetSelectedSpansCore(SelectionSpan[] selectedSpans) { if (_textView.Selection.Mode == TextSelectionMode.Box) { var selectedSpan = selectedSpans[0]; _textView.Caret.MoveTo(selectedSpan.CaretPoint); if (selectedSpan.Length == 0) { _textView.Selection.Clear(); } else { _textView.Selection.Select(selectedSpan.AnchorPoint, selectedSpan.ActivePoint); } return; } var selections = new Selection[selectedSpans.Length]; for (var caretIndex = 0; caretIndex < selectedSpans.Length; caretIndex++) { selections[caretIndex] = GetSelection(selectedSpans[caretIndex]); } var broker = _textView.GetMultiSelectionBroker(); broker.SetSelectionRange(selections, selections[0]); } private static SelectionSpan GetSelectedSpan(Selection selection) { return new SelectionSpan(selection.InsertionPoint, selection.AnchorPoint, selection.ActivePoint); } private static Selection GetSelection(SelectionSpan span) { return new Selection(span.CaretPoint, span.AnchorPoint, span.ActivePoint); } } [ImportingConstructor] internal MultiSelectionUtilFactory(Lazy<IVimHost> vimHost) : base(vimHost) { } ISelectionUtil ISelectionUtilFactory.GetSelectionUtil(ITextView textView) { - return new MultiSelectionUtil(textView); + var propertyCollection = textView.Properties; + return propertyCollection.GetOrCreateSingletonProperty(s_key, + () => new MultiSelectionUtil(textView)); } } } #endif
VsVim/VsVim
bbf1be1b0eb64035831dac1e33986f98654831fc
Map anchor point to current snapshot
diff --git a/Src/VimCore/CommonOperations.fs b/Src/VimCore/CommonOperations.fs index 652f96f..aa2baf5 100644 --- a/Src/VimCore/CommonOperations.fs +++ b/Src/VimCore/CommonOperations.fs @@ -2204,754 +2204,754 @@ type internal CommonOperations member x.RaiseSearchResultMessage searchResult = CommonUtil.RaiseSearchResultMessage _statusUtil searchResult /// Record last change start and end positions /// (spans must be from different snapshots) member x.RecordLastChange (oldSpan: SnapshotSpan) (newSpan: SnapshotSpan) = Contract.Requires(oldSpan.Snapshot <> newSpan.Snapshot) x.RecordLastChangeOrYank oldSpan newSpan /// Record last yank start and end positions member x.RecordLastYank (span: SnapshotSpan) = // If ':set clipboard=unnamed' is in effect, copy the yanked span to // the clipboard using the editor to preserve formatting. Feature // requested in issue #1920. if Util.IsFlagSet _globalSettings.ClipboardOptions ClipboardOptions.Unnamed then SelectionSpan.FromSpan(span.End, span, isReversed = false) |> TextViewUtil.SelectSpan _textView _editorOperations.CopySelection() |> ignore TextViewUtil.ClearSelection _textView x.RecordLastChangeOrYank span span /// Record last change or yankstart and end positions /// (it is a yank if the old span and the new span are the same) member x.RecordLastChangeOrYank oldSpan newSpan = let startPoint = SnapshotSpanUtil.GetStartPoint newSpan let endPoint = SnapshotSpanUtil.GetEndPoint newSpan let endPoint = match SnapshotSpanUtil.GetLastIncludedPoint newSpan with | Some point -> if SnapshotPointUtil.IsInsideLineBreak point then point else endPoint | None -> endPoint _vimTextBuffer.LastChangeOrYankStart <- Some startPoint _vimTextBuffer.LastChangeOrYankEnd <- Some endPoint let lineRange = if newSpan.Length = 0 then oldSpan else newSpan |> SnapshotLineRange.CreateForSpan let lineCount = lineRange.Count if lineCount >= 3 then if newSpan.Length = 0 then Resources.Common_LinesDeleted lineCount elif oldSpan = newSpan then Resources.Common_LinesYanked lineCount else Resources.Common_LinesChanged lineCount |> _statusUtil.OnStatus /// Undo 'count' operations in the ITextBuffer and ensure the caret is on the screen /// after the undo completes member x.Undo count = x.EnsureUndoHasView() _undoRedoOperations.Undo count x.AdjustCaretForVirtualEdit() x.EnsureAtPoint x.CaretPoint ViewFlags.Standard /// Redo 'count' operations in the ITextBuffer and ensure the caret is on the screen /// after the redo completes member x.Redo count = x.EnsureUndoHasView() _undoRedoOperations.Redo count x.AdjustCaretForVirtualEdit() x.EnsureAtPoint x.CaretPoint ViewFlags.Standard /// Restore spaces to caret, or move to start of line if 'startofline' is set member x.RestoreSpacesToCaret (spacesToCaret: int) (useStartOfLine: bool) = if useStartOfLine && _globalSettings.StartOfLine then let point = SnapshotLineUtil.GetFirstNonBlankOrEnd x.CaretLine TextViewUtil.MoveCaretToPoint _textView point else let virtualColumn = if _vimTextBuffer.UseVirtualSpace then VirtualSnapshotColumn.GetColumnForSpaces(x.CaretLine, spacesToCaret, _localSettings.TabStop) else let column = SnapshotColumn.GetColumnForSpacesOrEnd(x.CaretLine, spacesToCaret, _localSettings.TabStop) VirtualSnapshotColumn(column) x.MoveCaretToVirtualPoint virtualColumn.VirtualStartPoint ViewFlags.VirtualEdit x.MaintainCaretColumn <- MaintainCaretColumn.Spaces spacesToCaret /// Synchronously ensure that the given view properties are met at the given point member x.EnsureAtPointSync point viewFlags = let point = x.MapPointNegativeToCurrentSnapshot point if Util.IsFlagSet viewFlags ViewFlags.TextExpanded then x.EnsurePointExpanded point if Util.IsFlagSet viewFlags ViewFlags.Visible then x.EnsurePointVisible point if Util.IsFlagSet viewFlags ViewFlags.ScrollOffset then x.AdjustTextViewForScrollOffsetAtPoint point if Util.IsFlagSet viewFlags ViewFlags.VirtualEdit && point.Position = x.CaretPoint.Position then x.AdjustCaretForVirtualEdit() /// Ensure the view properties are met at the caret member x.EnsureAtCaret viewFlags = if _vimBufferData.CaretIndex = 0 then x.DoActionWhenReady (fun () -> x.EnsureAtPointSync x.CaretPoint viewFlags) /// Ensure that the given view properties are met at the given point member x.EnsureAtPoint point viewFlags = x.DoActionWhenReady (fun () -> x.EnsureAtPointSync point viewFlags) /// Ensure the given SnapshotPoint is not in a collapsed region on the screen member x.EnsurePointExpanded point = match _outliningManager with | None -> () | Some outliningManager -> let span = SnapshotSpan(point, 0) outliningManager.ExpandAll(span, fun _ -> true) |> ignore /// Ensure the point is on screen / visible member x.EnsurePointVisible (point: SnapshotPoint) = TextViewUtil.CheckScrollToPoint _textView point if point.Position = x.CaretPoint.Position then TextViewUtil.EnsureCaretOnScreen _textView else _vimHost.EnsureVisible _textView point member x.GetRegisterName name = match name with | Some name -> name | None -> if Util.IsFlagSet _globalSettings.ClipboardOptions ClipboardOptions.Unnamed then RegisterName.SelectionAndDrop SelectionAndDropRegister.Star else RegisterName.Unnamed member x.GetRegister name = let name = x.GetRegisterName name _registerMap.GetRegister name /// Updates the given register with the specified value. This will also update /// other registers based on the type of update that is being performed. See /// :help registers for the full details member x.SetRegisterValue (name: RegisterName option) operation (value: RegisterValue) = let name, isUnnamedOrMissing, isMissing = match name with | None -> x.GetRegisterName None, true, true | Some name -> name, name = RegisterName.Unnamed, false if name <> RegisterName.Blackhole then _registerMap.SetRegisterValue name value // If this is not the unnamed register then the unnamed register // needs to be updated to the value of the register we just set // (or appended to). if name <> RegisterName.Unnamed then _registerMap.GetRegister name |> (fun register -> register.RegisterValue) |> _registerMap.SetRegisterValue RegisterName.Unnamed let hasNewLine = match value.StringData with | StringData.Block col -> Seq.exists EditUtil.HasNewLine col | StringData.Simple str -> EditUtil.HasNewLine str // Performs a numbered delete. Shifts all of the values down and puts // the new value into register 1 // // The documentation for registers 1-9 says this doesn't occur when a named // register is used. Actual behavior shows this is not the case. let doNumberedDelete () = for i in [9;8;7;6;5;4;3;2] do let cur = RegisterNameUtil.NumberToRegister i |> Option.get let prev = RegisterNameUtil.NumberToRegister (i - 1) |> Option.get let prevRegister = _registerMap.GetRegister prev _registerMap.SetRegisterValue cur prevRegister.RegisterValue _registerMap.SetRegisterValue (RegisterName.Numbered NumberedRegister.Number1) value // Update the numbered register based on the type of the operation match operation with | RegisterOperation.Delete -> if hasNewLine then doNumberedDelete() // Use small delete register unless a register was explicitly named else if isMissing then _registerMap.SetRegisterValue RegisterName.SmallDelete value | RegisterOperation.BigDelete -> doNumberedDelete() if not hasNewLine && name = RegisterName.Unnamed then _registerMap.SetRegisterValue RegisterName.SmallDelete value | RegisterOperation.Yank -> // If the register name was missing or explicitly the unnamed register then it needs // to update register 0. if isUnnamedOrMissing then _registerMap.SetRegisterValue (RegisterName.Numbered NumberedRegister.Number0) value /// Toggle the use of typing language characters for insert or search /// (see vim ':help i_CTRL-^' and ':help c_CTRL-^') member x.ToggleLanguage isForInsert = let keyMap = _vimBufferData.VimTextBuffer.LocalKeyMap let languageMappings = keyMap.GetKeyMappings(KeyRemapMode.Language, includeGlobal = true) let languageMappingsAreDefined = not (Seq.isEmpty languageMappings) if isForInsert || _globalSettings.ImeSearch = -1 then if languageMappingsAreDefined then match _globalSettings.ImeInsert with | 1 -> _globalSettings.ImeInsert <- 0 | _ -> _globalSettings.ImeInsert <- 1 else match _globalSettings.ImeInsert with | 2 -> _globalSettings.ImeInsert <- 0 | _ -> _globalSettings.ImeInsert <- 2 else if languageMappingsAreDefined then match _globalSettings.ImeSearch with | 1 -> _globalSettings.ImeSearch <- 0 | _ -> _globalSettings.ImeSearch <- 1 else match _globalSettings.ImeSearch with | 2 -> _globalSettings.ImeSearch <- 0 | _ -> _globalSettings.ImeSearch <- 2 /// Map the specified point with negative tracking to the current snapshot member x.MapPointNegativeToCurrentSnapshot (point: SnapshotPoint) = x.MapPointToCurrentSnapshot point PointTrackingMode.Negative /// Map the specified point with positive tracking to the current snapshot member x.MapPointPositiveToCurrentSnapshot (point: SnapshotPoint) = x.MapPointToCurrentSnapshot point PointTrackingMode.Positive /// Map the specified point with the specified tracking to the current snapshot member x.MapPointToCurrentSnapshot (point: SnapshotPoint) (pointTrackingMode: PointTrackingMode) = let snapshot = _textBuffer.CurrentSnapshot TrackingPointUtil.GetPointInSnapshot point pointTrackingMode snapshot |> Option.defaultValue (SnapshotPoint(snapshot, min point.Position snapshot.Length)) /// Map the specified caret point to the current snapshot member x.MapCaretPointToCurrentSnapshot (point: VirtualSnapshotPoint) = if _vimTextBuffer.UseVirtualSpace then let snapshot = _textBuffer.CurrentSnapshot let pointTrackingMode = PointTrackingMode.Negative match TrackingPointUtil.GetVirtualPointInSnapshot point pointTrackingMode snapshot with | Some point -> point | None -> let defaultPoint = SnapshotPoint(snapshot, min point.Position.Position snapshot.Length) VirtualSnapshotPoint(defaultPoint, point.VirtualSpaces) else point.Position |> x.MapPointNegativeToCurrentSnapshot |> VirtualSnapshotPointUtil.OfPoint /// Map the specified selected span to the current snapshot member x.MapSelectedSpanToCurrentSnapshot (span: SelectionSpan) = let caretPoint = x.MapCaretPointToCurrentSnapshot span.CaretPoint let anchorPoint = x.MapCaretPointToCurrentSnapshot span.AnchorPoint let activcePoint = x.MapCaretPointToCurrentSnapshot span.ActivePoint SelectionSpan(caretPoint, anchorPoint, activcePoint) /// Add a new caret at the specified point member x.AddCaretAtPoint (point: VirtualSnapshotPoint) = let contains = VirtualSnapshotSpanUtil.ContainsOrEndsWith let isContainedByExistingSpan = x.SelectedSpans |> Seq.exists (fun span -> contains span.Span point) let remainingSpans = x.SelectedSpans |> Seq.filter (fun span -> not (contains span.Span point)) |> Seq.toArray if remainingSpans.Length > 0 || not isContainedByExistingSpan then seq { yield! remainingSpans if not isContainedByExistingSpan then yield SelectionSpan(point) } |> x.SetSelectedSpans /// Add the specified selected span member x.AddSelectedSpan selectedSpan = seq { yield! x.SelectedSpans yield selectedSpan } |> x.SetSelectedSpans /// Add a new caret at the mouse point member x.AddCaretAtMousePoint () = match x.MousePoint with | Some mousePoint -> x.AddCaretAtPoint mousePoint | None -> () /// Add a caret or selection on an adjacent line in the specified direction member x.AddCaretOrSelectionOnAdjacentLine direction = // Get the selected spans sorted by caret point. let selectedSpans = x.SelectedSpans |> Seq.sortBy (fun span -> span.CaretPoint.Position.Position) |> Seq.toList // Add a selection on the specified line number in the same column as // the primary caret. let addSelectionOnLineNumber lineNumber = let primarySelectedSpan = x.PrimarySelectedSpan let snapshot = primarySelectedSpan.CaretPoint.Position.Snapshot let line = SnapshotUtil.GetLine snapshot lineNumber let getRelativePoint point = let spaces = x.GetSpacesToVirtualPoint point let column = x.GetAppropriateColumnForSpaces line spaces column.VirtualStartPoint let caretPoint = getRelativePoint primarySelectedSpan.CaretPoint let anchorPoint = getRelativePoint primarySelectedSpan.AnchorPoint let activePoint = getRelativePoint primarySelectedSpan.ActivePoint SelectionSpan(caretPoint, anchorPoint, activePoint) |> x.AddSelectedSpan // Choose an appropriate line to add the caret on. match direction with | Direction.Up -> let firstLine = selectedSpans.[0].CaretPoint |> VirtualSnapshotPointUtil.GetContainingLine if firstLine.LineNumber > 0 then addSelectionOnLineNumber (firstLine.LineNumber - 1) | Direction.Down -> let lastLine = selectedSpans.[selectedSpans.Length - 1].CaretPoint |> VirtualSnapshotPointUtil.GetContainingLine let lastLineNumber = SnapshotUtil.GetLastNormalizedLineNumber lastLine.Snapshot if lastLine.LineNumber < lastLineNumber then addSelectionOnLineNumber (lastLine.LineNumber + 1) | _ -> () /// Run the specified action for all selections member x.RunForAllSelections action = // Unless there are multiple selections just do the action once and // return its result normally. if x.IsMultiSelectionSupported then let selectedSpans = x.SelectedSpans |> Seq.toList if selectedSpans.Length > 1 then x.RunForAllSelectionsCore action selectedSpans else action() else action() /// Run the specified action for the specified selected spans member x.RunForAllSelectionsCore action selectedSpans = // Get the current kind of visual mode, if any. let visualModeKind = _vimTextBuffer.ModeKind |> VisualKind.OfModeKind // Get any mode argument from the specified command result. let getModeArgument result = match result with | CommandResult.Completed modeSwitch -> match modeSwitch with | ModeSwitch.SwitchModeWithArgument (_, modeArgument) -> Some modeArgument | _ -> None | _ -> None // Get any linked transaction from the specified command result. let getLinkedTransaction result = match getModeArgument result with | Some modeArgument -> modeArgument.LinkedUndoTransaction | _ -> None // Get any visual selection from the specified command result. let getVisualSelection result = match getModeArgument result with | Some (ModeArgument.InitialVisualSelection (visualSelection, _)) -> _globalSettings.SelectionKind |> visualSelection.GetPrimarySelectedSpan |> Some | _ -> None // Get any switch to mode kind let getSwitchToModeKind result = match result with | CommandResult.Completed modeSwitch -> match modeSwitch with | ModeSwitch.SwitchMode modeKind -> Some modeKind | ModeSwitch.SwitchModeWithArgument (modeKind, _) -> Some modeKind | _ -> None | _ -> None // Get any switch to visual mode from the specifed command result. let getSwitchToVisualKind result = match getSwitchToModeKind result with | Some modeKind -> match modeKind with | ModeKind.VisualCharacter -> Some VisualKind.Character | ModeKind.VisualLine -> Some VisualKind.Line | ModeKind.VisualBlock -> Some VisualKind.Block | _ -> None | _ -> None // Create a linked undo transaction. let createTransaction () = let name = "MultiSelection" let flags = LinkedUndoTransactionFlags.CanBeEmpty _undoRedoOperations.CreateLinkedUndoTransactionWithFlags name flags // Run the action and complete any embedded linked transaction. let runActionAndCompleteTransaction action = let result = action() match getLinkedTransaction result with | Some linkedTransaction -> linkedTransaction.Complete() | None -> () result // Get the effective selected span. let getVisualSelectedSpan visualKind (oldSelectedSpan: SelectionSpan) = let oldSelectedSpan = x.MapSelectedSpanToCurrentSnapshot oldSelectedSpan let snapshot = _textView.TextSnapshot let oldAnchorPoint = oldSelectedSpan.AnchorPoint let anchorPoint = match _vimBufferData.VisualAnchorPoint with | Some trackingPoint -> match TrackingPointUtil.GetPoint snapshot trackingPoint with | Some point -> VirtualSnapshotPointUtil.OfPoint point | None -> oldAnchorPoint | None -> oldAnchorPoint let anchorPointChanged = oldAnchorPoint <> anchorPoint let caretPoint = x.CaretVirtualPoint let useVirtualSpace = _vimBufferData.VimTextBuffer.UseVirtualSpace let selectionKind = _globalSettings.SelectionKind let tabStop = _localSettings.TabStop let visualSelection = VisualSelection.CreateForVirtualPoints visualKind anchorPoint caretPoint tabStop useVirtualSpace let adjustSelection = match selectionKind with | SelectionKind.Exclusive -> true | SelectionKind.Inclusive -> oldSelectedSpan.IsReversed && oldSelectedSpan.Length <> 1 && not anchorPointChanged let visualSelection = if adjustSelection then visualSelection.AdjustForSelectionKind SelectionKind.Exclusive else visualSelection let span = visualSelection.GetPrimarySelectedSpan selectionKind if selectionKind = SelectionKind.Inclusive && span.Length = 1 && span.CaretPoint = span.Start then SelectionSpan(span.CaretPoint, span.Start, span.End) else span // Get the initial selected span for specified kind of visual mode. let getInitialSelection visualKind = let caretPoint = TextViewUtil.GetCaretVirtualPoint _textView let tabStop = _localSettings.TabStop let selectionKind = _globalSettings.SelectionKind let useVirtualSpace = _vimBufferData.VimTextBuffer.UseVirtualSpace let visualSelection = VisualSelection.CreateInitial visualKind caretPoint tabStop selectionKind useVirtualSpace visualSelection.GetPrimarySelectedSpan selectionKind // Collect the command result and new selected span or any embedded // visual span, if present. let getResultingSpan oldSelectedSpan result = match getSwitchToModeKind result with | Some modeKind when VisualKind.OfModeKind modeKind |> Option.isNone -> SelectionSpan(x.CaretVirtualPoint) | _ -> match getSwitchToVisualKind result with | Some visualKind -> getInitialSelection visualKind | None -> match visualModeKind with | Some modeKind -> getVisualSelectedSpan modeKind oldSelectedSpan | None -> match getVisualSelection result with | Some selectedSpan -> selectedSpan | None -> x.PrimarySelectedSpan // Set a temporary visual anchor point. let setVisualAnchorPoint (anchorPoint: VirtualSnapshotPoint) = if Option.isSome visualModeKind then - let snapshot = _textBuffer.CurrentSnapshot + let snapshot = anchorPoint.Position.Snapshot let position = anchorPoint.Position.Position let trackingPoint = snapshot.CreateTrackingPoint(position, PointTrackingMode.Negative) |> Some _vimBufferData.VisualAnchorPoint <- trackingPoint // Get the results for all actions. let getResults () = seq { let indexedSpans = selectedSpans |> Seq.mapi (fun index span -> index, span) // Iterate over all selections. for index, oldSelectedSpan in indexedSpans do // Set the buffer local caret index. _vimBufferData.CaretIndex <- index - // Set the visual anchor point. - setVisualAnchorPoint oldSelectedSpan.AnchorPoint - - // Temporarily set the real caret and selection. - x.MapSelectedSpanToCurrentSnapshot oldSelectedSpan - |> x.SetTemporarySelectedSpan + // Temporarily set the visual anchor point, the real caret + // and the real selection. + let selectedSpan = + x.MapSelectedSpanToCurrentSnapshot oldSelectedSpan + setVisualAnchorPoint selectedSpan.AnchorPoint + x.SetTemporarySelectedSpan selectedSpan // Run the action once and get the result. let result = runActionAndCompleteTransaction action // Get the resulting span. let newSelectedSpan = getResultingSpan oldSelectedSpan result let newAnchorPoint = _vimBufferData.VisualAnchorPoint yield result, newSelectedSpan, newAnchorPoint } |> Seq.toList // Do the action for all selections let doActions () = // Create a linked transaction for the overall operation, but // protect against leaving it open if it isn't used. let transaction = createTransaction() let mutable usedTransaction = false try // Run the action for each selected span. let results = getResults() // Extract the resulting selected spans and set them. results |> Seq.map (fun (_, selectedSpan, _) -> selectedSpan) |> Seq.map x.MapSelectedSpanToCurrentSnapshot |> x.SetSelectedSpans // Extract the first command result and anchor point. let firstResult, _, firstAnchorPoint = results |> Seq.head // Update the real visual anchor point. _vimBufferData.VisualAnchorPoint <- firstAnchorPoint // Translate any mode argument with a transaction. let newModeArgument = match getModeArgument firstResult with | Some (ModeArgument.InsertWithCountAndNewLine (count, _)) -> Some (ModeArgument.InsertWithCountAndNewLine (count, transaction)) | Some (ModeArgument.InsertWithTransaction _) -> Some (ModeArgument.InsertWithTransaction transaction) | _ -> None // Handle command result. match newModeArgument with | Some modeArgument -> // The individual command ended in a linked transaction. Enter // insert mode with the overall linked transaction instead. usedTransaction <- true (ModeKind.Insert, modeArgument) |> ModeSwitch.SwitchModeWithArgument |> CommandResult.Completed | None -> // Otherwise just return the first result. firstResult finally // Maybe complete the transaction. if not usedTransaction then transaction.Complete() // Do the actions for each selection being sure to restore the old // caret index at the end. let wrapDoActions () = let oldCaretIndex = _vimBufferData.CaretIndex try use bulkOperation = _bulkOperations.BeginBulkOperation() doActions() finally _vimBufferData.CaretIndex <- oldCaretIndex // Ensure view properties at the primary caret. x.EnsureAtCaret ViewFlags.Standard // Body starts here. wrapDoActions() interface ICommonOperations with member x.VimBufferData = _vimBufferData member x.TextView = _textView member x.IsMultiSelectionSupported = x.IsMultiSelectionSupported member x.PrimarySelectedSpan = x.PrimarySelectedSpan member x.SelectedSpans = x.SelectedSpans member x.EditorOperations = _editorOperations member x.EditorOptions = _editorOptions member x.MousePoint = x.MousePoint member x.AddCaretAtPoint point = x.AddCaretAtPoint point member x.AddCaretAtMousePoint() = x.AddCaretAtMousePoint() member x.AddCaretOrSelectionOnAdjacentLine direction = x.AddCaretOrSelectionOnAdjacentLine direction member x.AdjustTextViewForScrollOffset() = x.AdjustTextViewForScrollOffset() member x.AdjustCaretForScrollOffset() = x.AdjustCaretForScrollOffset() member x.AdjustCaretForVirtualEdit() = x.AdjustCaretForVirtualEdit() member x.Beep() = x.Beep() member x.CloseWindowUnlessDirty() = x.CloseWindowUnlessDirty() member x.CreateRegisterValue point stringData operationKind = x.CreateRegisterValue point stringData operationKind member x.DeleteLines startLine count registerName = x.DeleteLines startLine count registerName member x.DoActionAsync action = x.DoActionAsync action member x.DoActionWhenReady action = x.DoActionWhenReady action member x.EnsureAtCaret viewFlags = x.EnsureAtCaret viewFlags member x.EnsureAtPoint point viewFlags = x.EnsureAtPoint point viewFlags member x.FillInVirtualSpace() = x.FillInVirtualSpace() member x.FilterLines range command = x.FilterLines range command member x.FormatCodeLines range = x.FormatCodeLines range member x.FormatTextLines range preserveCaretPosition = x.FormatTextLines range preserveCaretPosition member x.ForwardToFocusedWindow action = x.ForwardToFocusedWindow action member x.GetRegister registerName = x.GetRegister registerName member x.GetNewLineText point = x.GetNewLineText point member x.GetNewLineIndent contextLine newLine = x.GetNewLineIndent contextLine newLine member x.GetReplaceData point = x.GetReplaceData point member x.GetSpacesToCaret() = x.GetSpacesToCaret() member x.GetSpacesToPoint point = x.GetSpacesToPoint point member x.GetColumnForSpacesOrEnd contextLine spaces = x.GetColumnForSpacesOrEnd contextLine spaces member x.GetSpacesToVirtualColumn column = x.GetSpacesToVirtualColumn column member x.GetVirtualColumnForSpaces contextLine spaces = x.GetVirtualColumnForSpaces contextLine spaces member x.GoToLocalDeclaration() = x.GoToLocalDeclaration() member x.GoToGlobalDeclaration() = x.GoToGlobalDeclaration() member x.GoToFile() = x.GoToFile() member x.GoToFile name = x.GoToFile name member x.GoToFileInNewWindow() = x.GoToFileInNewWindow() member x.GoToFileInNewWindow name = x.GoToFileInNewWindow name member x.GoToDefinition() = x.GoToDefinition() member x.GoToNextTab direction count = x.GoToNextTab direction count member x.GoToTab index = x.GoToTab index member x.GoToTagInNewWindow folder ident = x.GoToTagInNewWindow folder ident member x.Join range kind = x.Join range kind member x.LoadFileIntoNewWindow file lineNumber columnNumber = x.LoadFileIntoNewWindow file lineNumber columnNumber member x.MoveCaret caretMovement = x.MoveCaret caretMovement member x.MoveCaretWithArrow caretMovement = x.MoveCaretWithArrow caretMovement member x.MoveCaretToColumn column viewFlags = x.MoveCaretToColumn column viewFlags member x.MoveCaretToVirtualColumn column viewFlags = x.MoveCaretToVirtualColumn column viewFlags member x.MoveCaretToPoint point viewFlags = x.MoveCaretToPoint point viewFlags member x.MoveCaretToVirtualPoint point viewFlags = x.MoveCaretToVirtualPoint point viewFlags member x.MoveCaretToMotionResult data = x.MoveCaretToMotionResult data member x.NavigateToPoint point = x.NavigateToPoint point member x.NormalizeBlanks text spacesToColumn = x.NormalizeBlanks text spacesToColumn member x.NormalizeBlanksAtColumn text column = x.NormalizeBlanksAtColumn text column member x.NormalizeBlanksForNewTabStop text spacesToColumn tabStop = x.NormalizeBlanksForNewTabStop text spacesToColumn tabStop member x.NormalizeBlanksToSpaces text spacesToColumn = x.NormalizeBlanksToSpaces text spacesToColumn member x.OnStatusFitToWindow message = x.OnStatusFitToWindow message member x.OpenLinkUnderCaret() = x.OpenLinkUnderCaret() member x.Put point stringData opKind = x.Put point stringData opKind member x.RaiseSearchResultMessage searchResult = x.RaiseSearchResultMessage searchResult member x.RecordLastChange oldSpan newSpan = x.RecordLastChange oldSpan newSpan member x.RecordLastYank span = x.RecordLastYank span member x.Redo count = x.Redo count member x.RestoreSpacesToCaret spacesToCaret useStartOfLine = x.RestoreSpacesToCaret spacesToCaret useStartOfLine member x.RunForAllSelections action = x.RunForAllSelections action member x.SetSelectedSpans spans = x.SetSelectedSpans spans member x.SetRegisterValue name operation value = x.SetRegisterValue name operation value member x.ScrollLines dir count = x.ScrollLines dir count member x.ShiftLineBlockLeft col multiplier = x.ShiftLineBlockLeft col multiplier member x.ShiftLineBlockRight col multiplier = x.ShiftLineBlockRight col multiplier member x.ShiftLineRangeLeft range multiplier = x.ShiftLineRangeLeft range multiplier member x.ShiftLineRangeRight range multiplier = x.ShiftLineRangeRight range multiplier member x.SortLines range reverseOrder flags pattern = x.SortLines range reverseOrder flags pattern member x.Substitute pattern replace range flags = x.Substitute pattern replace range flags member x.ToggleLanguage isForInsert = x.ToggleLanguage isForInsert member x.MapPointNegativeToCurrentSnapshot point = x.MapPointNegativeToCurrentSnapshot point member x.MapPointPositiveToCurrentSnapshot point = x.MapPointPositiveToCurrentSnapshot point member x.MapCaretPointToCurrentSnapshot point = x.MapCaretPointToCurrentSnapshot point member x.MapSelectedSpanToCurrentSnapshot span = x.MapSelectedSpanToCurrentSnapshot span member x.Undo count = x.Undo count [<CLIEvent>] member x.SelectedSpansSet = _selectedSpansSetEvent.Publish [<Export(typeof<ICommonOperationsFactory>)>] type CommonOperationsFactory [<ImportingConstructor>] ( _editorOperationsFactoryService: IEditorOperationsFactoryService, _outliningManagerService: IOutliningManagerService, _undoManagerProvider: ITextBufferUndoManagerProvider, _mouseDevice: IMouseDevice, _bulkOperations: IBulkOperations ) as this = /// Use an object instance as a key. Makes it harder for components to ignore this /// service and instead manually query by a predefined key let _key = System.Object() /// Create an ICommonOperations instance for the given VimBufferData member x.CreateCommonOperations (vimBufferData: IVimBufferData) = let textView = vimBufferData.TextView let editorOperations = _editorOperationsFactoryService.GetEditorOperations(textView) let outlining = // This will return null in ITextBuffer instances where there is no IOutliningManager such // as TFS annotated buffers. let ret = _outliningManagerService.GetOutliningManager(textView) if ret = null then None else Some ret CommonOperations(this, vimBufferData, editorOperations, outlining, _mouseDevice, _bulkOperations) :> ICommonOperations /// Get or create the ICommonOperations for the given buffer member x.GetCommonOperations (bufferData: IVimBufferData) = let properties = bufferData.TextView.Properties properties.GetOrCreateSingletonProperty(_key, (fun () -> x.CreateCommonOperations bufferData)) interface ICommonOperationsFactory with member x.GetCommonOperations bufferData = x.GetCommonOperations bufferData
VsVim/VsVim
4bbe13cea84deefa8b41f6a0c94d6ebf7bbbd9d5
Handle special case text input in normal and visual modes
diff --git a/Src/VimCore/KeyInput.fs b/Src/VimCore/KeyInput.fs index fdd5830..c65c2e5 100644 --- a/Src/VimCore/KeyInput.fs +++ b/Src/VimCore/KeyInput.fs @@ -1,491 +1,501 @@ #light namespace Vim open System.Runtime.InteropServices [<Sealed>] type KeyInput ( _key: VimKey, _modKey: VimKeyModifiers, _literal: char option ) = member x.Char = match _literal with | Some c -> c | None -> CharUtil.MinValue member x.RawChar = _literal member x.Key = _key member x.KeyModifiers = _modKey member x.HasKeyModifiers = _modKey <> VimKeyModifiers.None member x.IsDigit = match _literal with | Some c -> CharUtil.IsDigit c | _ -> false /// Is this an arrow key? member x.IsArrowKey = VimKeyUtil.IsArrowKey _key /// Is this a function key member x.IsFunctionKey = VimKeyUtil.IsFunctionKey _key /// Is this a mouse key member x.IsMouseKey = VimKeyUtil.IsMouseKey _key /// In general Vim keys compare ordinally. The one exception is when the control /// modifier is applied to a letter key. In that case the keys compare in a case /// insensitive fashion. /// /// This is demonstratable in a couple of areas. One simple one is using the /// the CTRL-F command (scroll down). It has the same behavior with capital /// or lower case F. member x.CompareTo (right: KeyInput) = if obj.ReferenceEquals(right, null) then 1 else let left = x let comp = compare left.KeyModifiers right.KeyModifiers if comp <> 0 then comp else let comp = compare left.Char right.Char if comp <> 0 then comp else compare left.Key right.Key override x.GetHashCode() = HashUtil.Combine3 (x.Char.GetHashCode()) (x.Key.GetHashCode()) (x.KeyModifiers.GetHashCode()) override x.Equals(obj) = match obj with | :? KeyInput as other -> 0 = x.CompareTo other | _ -> false override x.ToString() = let displayChar = match _literal with | Some c -> StringUtil.GetDisplayString (string(c)) | None -> "none" System.String.Format("{0}:{1}:{2}", displayChar, x.Key, x.KeyModifiers) static member DefaultValue = KeyInput(VimKey.None, VimKeyModifiers.None, None) static member op_Equality(this,other) = System.Collections.Generic.EqualityComparer<KeyInput>.Default.Equals(this,other) static member op_Inequality(this,other) = not (System.Collections.Generic.EqualityComparer<KeyInput>.Default.Equals(this,other)) interface System.IComparable with member x.CompareTo yObj = match yObj with | :? KeyInput as y -> x.CompareTo y | _ -> invalidArg "yObj" "Cannot compare values of different types" interface System.IEquatable<KeyInput> with member x.Equals other = 0 = x.CompareTo other interface System.IComparable<KeyInput> with member x.CompareTo other = x.CompareTo other [<Sealed>] type KeyInputData ( _keyInput: KeyInput, _wasMapped: bool ) = member x.KeyInput = _keyInput member x.WasMapped = _wasMapped static member Create keyInput wasMapped = KeyInputData(keyInput, wasMapped) override x.ToString() = System.String.Format("{0}:{1}", x.KeyInput, x.WasMapped) module KeyInputUtil = [<Literal>] let CharLettersLower = "abcdefghijklmnopqrstuvwxyz" [<Literal>] let CharLettersUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" [<Literal>] let CharLettersExtra = " !@#$%^&*()[]{}-_=+\\|'\",<>./?:;`~1234567890" let RawCharData = CharLettersLower + CharLettersUpper + CharLettersExtra /// Mapping of all VimKey instances with their associated char if one exists. let VimKeyRawData = [ (VimKey.Back, Some CharCodes.Backspace) (VimKey.Enter, Some CharCodes.Enter) (VimKey.Escape, Some CharCodes.Escape) (VimKey.Left, None) (VimKey.Up, None) (VimKey.Right, None) (VimKey.Down, None) (VimKey.Delete, Some (CharUtil.OfAsciiValue 127uy)) (VimKey.Help, None) (VimKey.End, None) (VimKey.PageUp, None) (VimKey.PageDown, None) (VimKey.Insert, None) (VimKey.Home, None) (VimKey.F1, None) (VimKey.F2, None) (VimKey.F3, None) (VimKey.F4, None) (VimKey.F5, None) (VimKey.F6, None) (VimKey.F7, None) (VimKey.F8, None) (VimKey.F9, None) (VimKey.F10, None) (VimKey.F11, None) (VimKey.F12, None) (VimKey.KeypadDecimal, None) (VimKey.KeypadEnter, None) (VimKey.Keypad0, Some '0') (VimKey.Keypad1, Some '1') (VimKey.Keypad2, Some '2') (VimKey.Keypad3, Some '3') (VimKey.Keypad4, Some '4') (VimKey.Keypad5, Some '5') (VimKey.Keypad6, Some '6') (VimKey.Keypad7, Some '7') (VimKey.Keypad8, Some '8') (VimKey.Keypad9, Some '9') (VimKey.KeypadPlus, Some '+') (VimKey.KeypadMinus, Some '-') (VimKey.KeypadDivide, Some '/') (VimKey.KeypadMultiply, Some '*') (VimKey.LineFeed, Some (CharUtil.OfAsciiValue 10uy)) (VimKey.Null, Some (CharUtil.OfAsciiValue 0uy)) (VimKey.Tab, Some '\t') (VimKey.Nop, None) (VimKey.LeftMouse, None) (VimKey.LeftDrag, None) (VimKey.LeftRelease, None) (VimKey.MiddleMouse, None) (VimKey.MiddleDrag, None) (VimKey.MiddleRelease, None) (VimKey.RightMouse, None) (VimKey.RightDrag, None) (VimKey.RightRelease, None) (VimKey.X1Mouse, None) (VimKey.X1Drag, None) (VimKey.X1Release, None) (VimKey.X2Mouse, None) (VimKey.X2Drag, None) (VimKey.X2Release, None)] /// This is a mapping of the supported control character mappings in vim. The list of /// supported items is described here /// /// http://vimhelp.appspot.com/vim_faq.txt.html#faq-20.5 /// /// This map is useful when applying a Control modifier to char value. It produces the /// Vim character expected for such an application let ControlCharToKeyInputMap = // First build up the alpha characters let alpha = seq { let baseChar = int 'a' let baseCode = 0x1 for i = 0 to 25 do let letter = char (baseChar + i) let vimKey = match letter with | 'j' -> VimKey.LineFeed | 'm' -> VimKey.Enter | 'i' -> VimKey.Tab | _ -> VimKey.RawCharacter let c = let code = baseCode + i char code yield (letter, KeyInput(vimKey, VimKeyModifiers.None, Some c)) } let other = [ ('@', VimKey.Null, 0x00) // <Null> ('[', VimKey.Escape, 0x1B) // <Escape> ('\\', VimKey.RawCharacter, 0x1C) // <C-\> (']', VimKey.RawCharacter, 0x1D) // <C-]> ('^', VimKey.RawCharacter, 0x1E) // <C-^> ('_', VimKey.RawCharacter, 0x1F) // <C-_> ('?', VimKey.RawCharacter, 0x7F) // <C-?> ] |> Seq.map (fun (c, key, code) -> let controlChar = CharUtil.OfAsciiValue (byte code) let keyInput = KeyInput(key, VimKeyModifiers.None, Some controlChar) (c, keyInput)) Seq.append alpha other |> Map.ofSeq /// This is the set of predefined KeyInput values that Vim cares about let VimKeyInputList = let rawSeq = RawCharData |> Seq.map (fun c -> KeyInput(VimKey.RawCharacter, VimKeyModifiers.None, Some c)) let standardSeq = VimKeyRawData |> Seq.map (fun (key,charOpt) -> KeyInput(key, VimKeyModifiers.None, charOpt)) // When mapping the control keys only take the primary keys. Don't take any alternates because their // character is owned by a combination in the standard sequence. // // Only map RawCharacter values here. Anything which isn't a RawCharacter is already present in the // VimKeyRawData list let controlSeq = ControlCharToKeyInputMap |> Seq.map (fun pair -> pair.Value) |> Seq.filter (fun keyInput -> keyInput.Key = VimKey.RawCharacter) rawSeq |> Seq.append standardSeq |> Seq.append controlSeq |> List.ofSeq let VimKeyCharSet = VimKeyInputList |> Seq.map (fun ki -> ki.RawChar) |> SeqUtil.filterToSome |> Set.ofSeq let VimKeyCharList = VimKeyCharSet |> Set.toList /// Map for core characters to the KeyInput representation. While several keys /// may map to the same character their should be a primary KeyInput for every /// char. This map holds that mapping /// /// Even though key-notation lists <Del> and <Backslash> as being equivalents for /// chars they aren't in practice. When mapping by char we don't want to bind to /// these values and instead want the char version instead. Should only hit these /// when binding by name let CharToKeyInputMap = let inputs = VimKeyInputList |> Seq.map (fun ki -> OptionUtil.combine ki.RawChar ki ) |> SeqUtil.filterToSome |> Seq.filter (fun (_,ki) -> match ki.Key with | VimKey.Back -> false | VimKey.Delete -> false | _ -> not (VimKeyUtil.IsKeypadKey ki.Key)) |> List.ofSeq #if DEBUG let mutable debugMap: Map<char, KeyInput> = Map.empty for tuple in inputs do let c = fst tuple let found = Map.tryFind c debugMap if Option.isSome found then System.Diagnostics.Debug.Fail("This is the failure") debugMap <- Map.add c (snd tuple) debugMap #endif let map = inputs |> Map.ofSeq if map.Count <> inputs.Length then failwith Resources.KeyInput_DuplicateCharRepresentation map let CharToKeyInput c = match Map.tryFind c CharToKeyInputMap with | None -> KeyInput(VimKey.RawCharacter, VimKeyModifiers.None, Some c) | Some(ki) -> ki /// Map of the VimKey to KeyInput values. let VimKeyToKeyInputMap = VimKeyInputList |> Seq.filter (fun keyInput -> not keyInput.HasKeyModifiers) |> Seq.map (fun keyInput -> keyInput.Key, keyInput) |> Map.ofSeq let VimKeyToKeyInput vimKey = match Map.tryFind vimKey VimKeyToKeyInputMap with | None -> invalidArg "vimKey" Resources.KeyInput_InvalidVimKey | Some(ki) -> ki let ChangeKeyModifiersDangerous (ki:KeyInput) keyModifiers = KeyInput(ki.Key, keyModifiers, ki.RawChar) let NullKey = VimKeyToKeyInput VimKey.Null let LineFeedKey = VimKeyToKeyInput VimKey.LineFeed let EscapeKey = VimKeyToKeyInput VimKey.Escape let EnterKey = VimKeyToKeyInput VimKey.Enter let TabKey = CharToKeyInput '\t' /// Apply the modifiers to the given KeyInput and determine the result. This will /// not necessarily return a KeyInput with the modifier set. It attempts to unify /// certain ambiguous combinations. let ApplyKeyModifiers (keyInput: KeyInput) (targetModifiers: VimKeyModifiers) = let normalizeToUpper (keyInput: KeyInput) = match keyInput.RawChar with | None -> keyInput | Some c -> if CharUtil.IsLetter c && CharUtil.IsLower c then let c = CharUtil.ToUpper keyInput.Char let upperKeyInput = CharToKeyInput c ChangeKeyModifiersDangerous upperKeyInput keyInput.KeyModifiers else keyInput let normalizeShift (keyInput: KeyInput) = match keyInput.RawChar with | None -> keyInput | Some c -> if CharUtil.IsLetter c then // The shift key and letters is ambiguous. It can be represented equally well as // either of the following // // - Lower case 'a' + shift // - Upper case 'A' with no shift // // Vim doesn't distinguish between these two and unifies internally. This can be // demonstrated by playing with key mapping combinations (<S-A> and A). It's // convenient to have upper 'A' as a stand alone VimKey hence we choose to represent // that way and remove the shift modifier here let modifiers = Util.UnsetFlag keyInput.KeyModifiers VimKeyModifiers.Shift let keyInput = if CharUtil.IsLower keyInput.Char then // The shift modifier should promote a letter into the upper form let c = CharUtil.ToUpper keyInput.Char let upperKeyInput = CharToKeyInput c ChangeKeyModifiersDangerous upperKeyInput keyInput.KeyModifiers else // Ignore the shift modifier on anything which is not considered lower keyInput // Apply the remaining modifiers ChangeKeyModifiersDangerous keyInput modifiers elif (int c) < 0x100 && not (CharUtil.IsControl c) && c <> ' ' then // There is a set of chars for which the Shift modifier has no effect. If this is one of them then // don't apply the shift modifier to the final KeyInput let modifiers = Util.UnsetFlag keyInput.KeyModifiers VimKeyModifiers.Shift ChangeKeyModifiersDangerous keyInput modifiers else // Nothing special to do here keyInput let normalizeControl (keyInput: KeyInput) = if Util.IsFlagSet keyInput.KeyModifiers VimKeyModifiers.Alt then keyInput else match keyInput.RawChar with | None -> keyInput | Some c -> // When searching for the control keys make sure to look at the lower case // letters if this is a case of the shift modifier let c = if CharUtil.IsUpperLetter c then CharUtil.ToLower c else c // Map the known control cases back to the Vim defined behavior. This mapping intentionally removes any // Shift modifiers. No matter how CTRL-Q is produced the shift modifier isn't present on the vim key match Map.tryFind c ControlCharToKeyInputMap with | None -> keyInput | Some keyInput -> let modifiers = Util.UnsetFlag keyInput.KeyModifiers VimKeyModifiers.Control ChangeKeyModifiersDangerous keyInput modifiers let keyInput = ChangeKeyModifiersDangerous keyInput (targetModifiers ||| keyInput.KeyModifiers) if Util.IsFlagSet targetModifiers VimKeyModifiers.Alt then // The alt key preserves all modifiers and converts the char to uppercase. normalizeToUpper keyInput else // First normalize the shift case. let keyInput = if Util.IsFlagSet targetModifiers VimKeyModifiers.Shift then normalizeShift keyInput else keyInput // Next normalize the control case. let keyInput = if Util.IsFlagSet targetModifiers VimKeyModifiers.Control then normalizeControl keyInput else keyInput keyInput let ApplyKeyModifiersToKey vimKey modifiers = let keyInput = VimKeyToKeyInput vimKey ApplyKeyModifiers keyInput modifiers let ApplyKeyModifiersToChar c modifiers = let keyInput = CharToKeyInput c ApplyKeyModifiers keyInput modifiers let ApplyClickCount keyInput clickCount = let modifiers = match clickCount with | 2 -> VimKeyModifiers.Double | 3 -> VimKeyModifiers.Triple | 4 -> VimKeyModifiers.Quadruple | _ -> VimKeyModifiers.None ApplyKeyModifiers keyInput modifiers let NormalizeKeyModifiers (keyInput: KeyInput) = match keyInput.Key, keyInput.RawChar with | VimKey.RawCharacter, Some c -> ApplyKeyModifiersToChar c keyInput.KeyModifiers | key, _ -> ApplyKeyModifiersToKey key keyInput.KeyModifiers let CharWithControlToKeyInput ch = let keyInput = ch |> CharToKeyInput ApplyKeyModifiers keyInput VimKeyModifiers.Control let CharWithAltToKeyInput ch = let keyInput = ch |> CharToKeyInput ApplyKeyModifiers keyInput VimKeyModifiers.Alt let GetNonKeypadEquivalent (keyInput: KeyInput) = let apply c = let keyInput = CharToKeyInput c ApplyKeyModifiers keyInput keyInput.KeyModifiers |> Some match keyInput.Key with | VimKey.Keypad0 -> apply '0' | VimKey.Keypad1 -> apply '1' | VimKey.Keypad2 -> apply '2' | VimKey.Keypad3 -> apply '3' | VimKey.Keypad4 -> apply '4' | VimKey.Keypad5 -> apply '5' | VimKey.Keypad6 -> apply '6' | VimKey.Keypad7 -> apply '7' | VimKey.Keypad8 -> apply '8' | VimKey.Keypad9 -> apply '9' | VimKey.KeypadDecimal -> apply '.' | VimKey.KeypadDivide -> apply '/' | VimKey.KeypadMinus -> apply '-' | VimKey.KeypadMultiply -> apply '*' | VimKey.KeypadPlus -> apply '+' | VimKey.KeypadEnter -> ApplyKeyModifiers EnterKey keyInput.KeyModifiers |> Some | _ -> None let IsCore (keyInput: KeyInput) = if Util.IsFlagSet keyInput.KeyModifiers VimKeyModifiers.Alt then // No key or char with the alt modifier is a core key input. false elif keyInput.Key <> VimKey.RawCharacter then // Any standard vim key with or without modifiers is a core key input. true elif not keyInput.HasKeyModifiers && Option.isSome keyInput.RawChar && VimKeyCharSet.Contains keyInput.Char then // Any standard vim char without modifiers is a core key input. true else false + + let IsTextInput (keyInput: KeyInput) = + if keyInput.KeyModifiers <> VimKeyModifiers.None then + // Any key input with modifiers is not an input key. + false + elif CharUtil.IsPrintable keyInput.Char then + // Any printable character is an input key. + true + else + false diff --git a/Src/VimCore/KeyInput.fsi b/Src/VimCore/KeyInput.fsi index fc3288a..e481989 100644 --- a/Src/VimCore/KeyInput.fsi +++ b/Src/VimCore/KeyInput.fsi @@ -1,131 +1,133 @@  #light namespace Vim /// Represents a key input by the user. This mapping is independent of keyboard /// layout and simply represents Vim's view of key input [<Sealed>] type KeyInput = /// The character representation of this input. If there is no character representation /// then Char.MinValue will be returend member Char: char /// Returns the actual backing character in the form of an option. Several keys /// don't have corresponding char values and will return None member RawChar: char option /// The VimKey for this KeyInput. member Key: VimKey /// The extra modifier keys applied to the VimKey value member KeyModifiers: VimKeyModifiers /// Whether the key has any key modifiers member HasKeyModifiers: bool /// Is the character for this KeyInput a digit member IsDigit: bool /// Is this an arrow key? member IsArrowKey: bool /// Is this a function key member IsFunctionKey: bool /// Is this a mouse key member IsMouseKey: bool /// Compare to another KeyInput value member CompareTo: other: KeyInput -> int /// The empty KeyInput. Used in places where a KeyInput is required but no /// good mapping exists static member DefaultValue: KeyInput static member op_Equality: KeyInput * KeyInput -> bool static member op_Inequality: KeyInput * KeyInput -> bool interface System.IComparable interface System.IComparable<KeyInput> interface System.IEquatable<KeyInput> /// Represents a key input together with whether the key input was the result /// of a mapping [<Sealed>] type KeyInputData = member KeyInput: KeyInput member WasMapped: bool static member Create: keyInput: KeyInput -> wasMapped: bool -> KeyInputData module KeyInputUtil = /// The Null Key: VimKey.Null val NullKey: KeyInput /// The LineFeed key: VimKey.LineFeed val LineFeedKey: KeyInput /// The Enter Key: VimKey.Enter val EnterKey: KeyInput /// The Escape Key: VimKey.Escape val EscapeKey: KeyInput /// The Tab Key: VimKey.Tab val TabKey: KeyInput /// The KeyInput for every VimKey in the system which is considered predefined val VimKeyInputList: KeyInput list /// The set of core characters val VimKeyCharSet: char Set /// The set of core characters as a list val VimKeyCharList: char list /// Apply the modifiers to the given KeyInput and determine the result. This will /// not necessarily return a KeyInput with the modifier set. It attempts to unify /// certain ambiguous combinations. val ApplyKeyModifiers: keyInput: KeyInput -> modifiers: VimKeyModifiers -> KeyInput /// Apply the modifiers to the given character val ApplyKeyModifiersToChar: c: char -> modifiers: VimKeyModifiers -> KeyInput /// Apply the modifiers to the given VimKey val ApplyKeyModifiersToKey: vimKey: VimKey -> modifiers: VimKeyModifiers -> KeyInput /// Apply a click count to the given key input val ApplyClickCount: keyInput: KeyInput -> clickCount: int -> KeyInput /// Normalize key modifiers, e.g. removing an irrelevant shift val NormalizeKeyModifiers: keyInput: KeyInput -> KeyInput /// Try and convert the given char to a KeyInput value val CharToKeyInput: c: char -> KeyInput /// Convert the passed in char to a KeyInput with Control val CharWithControlToKeyInput: c: char -> KeyInput /// Convert the passed in char to a KeyInput with Alt val CharWithAltToKeyInput: c: char -> KeyInput /// Convert the specified VimKey code to a KeyInput val VimKeyToKeyInput: vimKey: VimKey -> KeyInput /// Change the KeyModifiers associated with this KeyInput. Will not change the value /// of the underlying char. Although it may produce a KeyInput that makes no /// sense. For example it's very possible to have KeyInput('a', VimKeyModifiers.Shift) but /// it will be extremely hard to produce that in a keyboard (if possible at all). /// /// This method should be avoided. If you need to apply modifiers then use /// ApplyModifiers which uses Vim semantics when deciding how to apply the modifiers val ChangeKeyModifiersDangerous: keyInput: KeyInput -> modifiers: VimKeyModifiers -> KeyInput /// Get the alternate key for the given KeyInput if it's a key from the keypad val GetNonKeypadEquivalent: keyInput: KeyInput -> KeyInput option /// Whether this key input could appear in vim's standard bindings val IsCore: keyInput: KeyInput -> bool + /// Whether this key input could be inserted into a text buffer + val IsTextInput: keyInput: KeyInput -> bool diff --git a/Src/VimCore/Modes_Normal_NormalMode.fs b/Src/VimCore/Modes_Normal_NormalMode.fs index 7ffa20e..981b01b 100644 --- a/Src/VimCore/Modes_Normal_NormalMode.fs +++ b/Src/VimCore/Modes_Normal_NormalMode.fs @@ -1,412 +1,413 @@ #light namespace Vim.Modes.Normal open Vim open Vim.Modes open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Editor type internal NormalModeData = { Command: string InReplace: bool } type internal NormalMode ( _vimBufferData: IVimBufferData, _operations: ICommonOperations, _motionUtil: IMotionUtil, _runner: ICommandRunner, _capture: IMotionCapture, _incrementalSearch: IIncrementalSearch ) as this = let _vimTextBuffer = _vimBufferData.VimTextBuffer let _textView = _vimBufferData.TextView let _localSettings = _vimTextBuffer.LocalSettings let _globalSettings = _vimTextBuffer.GlobalSettings let _statusUtil = _vimBufferData.StatusUtil /// Reset state for data in Normal Mode static let EmptyData = { Command = StringUtil.Empty InReplace = false } /// Contains the state information for Normal mode let mutable _data = EmptyData /// This is the list of commands that have the same key binding as the selection /// commands and run when keymodel doesn't have startsel as a value let mutable _selectionAlternateCommands: CommandBinding list = List.empty let _eventHandlers = DisposableBag() /// The set of standard commands that are shared amongst all instances static let SharedStandardCommands = let normalSeq = seq { yield ("a", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.InsertAfterCaret) yield ("A", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.InsertAtEndOfLine) yield ("C", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.ChangeTillEndOfLine) yield ("cc", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.ChangeLines) yield ("dd", CommandFlags.Repeatable, NormalCommand.DeleteLines) yield ("D", CommandFlags.Repeatable, NormalCommand.DeleteTillEndOfLine) yield ("ga", CommandFlags.Special, NormalCommand.DisplayCharacterCodePoint) yield ("gf", CommandFlags.None, NormalCommand.GoToFileUnderCaret false) yield ("gJ", CommandFlags.Repeatable, NormalCommand.JoinLines JoinKind.KeepEmptySpaces) yield ("gh", CommandFlags.Special, NormalCommand.SwitchMode (ModeKind.SelectCharacter, ModeArgument.None)) yield ("gH", CommandFlags.Special, NormalCommand.SwitchMode (ModeKind.SelectLine, ModeArgument.None)) yield ("g<C-h>", CommandFlags.Special, NormalCommand.SwitchMode (ModeKind.SelectBlock, ModeArgument.None)) yield ("gI", CommandFlags.None, NormalCommand.InsertAtStartOfLine) yield ("gp", CommandFlags.Repeatable, NormalCommand.PutAfterCaret true) yield ("gP", CommandFlags.Repeatable, NormalCommand.PutBeforeCaret true) yield ("gt", CommandFlags.Special, NormalCommand.GoToNextTab SearchPath.Forward) yield ("gT", CommandFlags.Special, NormalCommand.GoToNextTab SearchPath.Backward) yield ("gv", CommandFlags.Special, NormalCommand.SwitchPreviousVisualMode) yield ("gn", CommandFlags.Special, NormalCommand.SelectNextMatch SearchPath.Forward) yield ("gN", CommandFlags.Special, NormalCommand.SelectNextMatch SearchPath.Backward) yield ("gugu", CommandFlags.Repeatable, NormalCommand.ChangeCaseCaretLine ChangeCharacterKind.ToLowerCase) yield ("guu", CommandFlags.Repeatable, NormalCommand.ChangeCaseCaretLine ChangeCharacterKind.ToLowerCase) yield ("gUgU", CommandFlags.Repeatable, NormalCommand.ChangeCaseCaretLine ChangeCharacterKind.ToUpperCase) yield ("gUU", CommandFlags.Repeatable, NormalCommand.ChangeCaseCaretLine ChangeCharacterKind.ToUpperCase) yield ("g~g~", CommandFlags.Repeatable, NormalCommand.ChangeCaseCaretLine ChangeCharacterKind.ToggleCase) yield ("g~~", CommandFlags.Repeatable, NormalCommand.ChangeCaseCaretLine ChangeCharacterKind.ToggleCase) yield ("g?g?", CommandFlags.Repeatable, NormalCommand.ChangeCaseCaretLine ChangeCharacterKind.Rot13) yield ("g??", CommandFlags.Repeatable, NormalCommand.ChangeCaseCaretLine ChangeCharacterKind.Rot13) yield ("g&", CommandFlags.Special, NormalCommand.RepeatLastSubstitute (true, true)) yield ("g<LeftMouse>", CommandFlags.Special, NormalCommand.GoToDefinitionUnderMouse) yield ("g8", CommandFlags.Special, NormalCommand.DisplayCharacterBytes) yield ("i", CommandFlags.None, NormalCommand.InsertBeforeCaret) yield ("I", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.InsertAtFirstNonBlank) yield ("J", CommandFlags.Repeatable, NormalCommand.JoinLines JoinKind.RemoveEmptySpaces) yield ("o", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.InsertLineBelow) yield ("O", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.InsertLineAbove) yield ("p", CommandFlags.Repeatable, NormalCommand.PutAfterCaret false) yield ("P", CommandFlags.Repeatable, NormalCommand.PutBeforeCaret false) yield ("R", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, NormalCommand.ReplaceAtCaret) yield ("s", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.SubstituteCharacterAtCaret) yield ("S", CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.ChangeLines) yield ("u", CommandFlags.Special, NormalCommand.Undo) yield ("U", CommandFlags.Special, NormalCommand.UndoLine) yield ("v", CommandFlags.Special, NormalCommand.SwitchModeVisualCommand VisualKind.Character) yield ("V", CommandFlags.Special, NormalCommand.SwitchModeVisualCommand VisualKind.Line) yield ("x", CommandFlags.Repeatable, NormalCommand.DeleteCharacterAtCaret) yield ("X", CommandFlags.Repeatable, NormalCommand.DeleteCharacterBeforeCaret) yield ("Y", CommandFlags.None, NormalCommand.YankLines) yield ("yy", CommandFlags.None, NormalCommand.YankLines) yield ("za", CommandFlags.Special, NormalCommand.ToggleFoldUnderCaret) yield ("zA", CommandFlags.Special, NormalCommand.ToggleAllFolds) yield ("zo", CommandFlags.Special, NormalCommand.OpenFoldUnderCaret) yield ("zO", CommandFlags.Special, NormalCommand.OpenAllFoldsUnderCaret) yield ("zc", CommandFlags.Special, NormalCommand.CloseFoldUnderCaret) yield ("zC", CommandFlags.Special, NormalCommand.CloseAllFoldsUnderCaret) yield ("zd", CommandFlags.Special, NormalCommand.DeleteFoldUnderCaret) yield ("zD", CommandFlags.Special, NormalCommand.DeleteAllFoldsUnderCaret) yield ("zE", CommandFlags.Special, NormalCommand.DeleteAllFoldsInBuffer) yield ("zF", CommandFlags.Special, NormalCommand.FoldLines) yield ("zM", CommandFlags.Special, NormalCommand.CloseAllFolds) yield ("zR", CommandFlags.Special, NormalCommand.OpenAllFolds) yield ("ZQ", CommandFlags.Special, NormalCommand.CloseBuffer) yield ("ZZ", CommandFlags.Special, NormalCommand.WriteBufferAndQuit) yield ("<Insert>", CommandFlags.None, NormalCommand.InsertBeforeCaret) yield ("<C-a>", CommandFlags.Repeatable, NormalCommand.AddToWord) yield ("<C-c>", CommandFlags.Repeatable, NormalCommand.CancelOperation) yield ("<C-g>", CommandFlags.Special, NormalCommand.PrintFileInformation) yield ("<C-i>", CommandFlags.Movement, NormalCommand.JumpToNewerPosition) yield ("<C-o>", CommandFlags.Movement, NormalCommand.JumpToOlderPosition) yield ("<C-PageDown>", CommandFlags.Special, NormalCommand.GoToNextTab SearchPath.Forward) yield ("<C-PageUp>", CommandFlags.Special, NormalCommand.GoToNextTab SearchPath.Backward) yield ("<C-q>", CommandFlags.Special, NormalCommand.SwitchModeVisualCommand VisualKind.Block) yield ("<C-r>", CommandFlags.Special, NormalCommand.Redo) yield ("<C-v>", CommandFlags.Special, NormalCommand.SwitchModeVisualCommand VisualKind.Block) yield ("<C-w>c", CommandFlags.None, NormalCommand.CloseWindow) yield ("<C-w><C-j>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Down) yield ("<C-w>j", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Down) yield ("<C-w><C-Down>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Down) yield ("<C-w><Down>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Down) yield ("<C-w><C-k>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Up) yield ("<C-w>k", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Up) yield ("<C-w><C-Up>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Up) yield ("<C-w><Up>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Up) yield ("<C-w><C-l>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Right) yield ("<C-w>l", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Right) yield ("<C-w><C-Right>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Right) yield ("<C-w><Right>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Right) yield ("<C-w><C-h>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Left) yield ("<C-w>h", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Left) yield ("<C-w><C-Left>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Left) yield ("<C-w><Left>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Left) yield ("<C-w>J", CommandFlags.None, NormalCommand.GoToWindow WindowKind.FarDown) yield ("<C-w>K", CommandFlags.None, NormalCommand.GoToWindow WindowKind.FarUp) yield ("<C-w>L", CommandFlags.None, NormalCommand.GoToWindow WindowKind.FarRight) yield ("<C-w>H", CommandFlags.None, NormalCommand.GoToWindow WindowKind.FarLeft) yield ("<C-w><C-t>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Top) yield ("<C-w>t", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Top) yield ("<C-w><C-b>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Bottom) yield ("<C-w>b", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Bottom) yield ("<C-w><C-p>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Recent) yield ("<C-w>p", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Recent) yield ("<C-w><C-w>", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Next) yield ("<C-w>w", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Next) yield ("<C-w>W", CommandFlags.None, NormalCommand.GoToWindow WindowKind.Previous) yield ("<C-w><C-s>", CommandFlags.None, NormalCommand.SplitViewHorizontally) yield ("<C-w>s", CommandFlags.None, NormalCommand.SplitViewHorizontally) yield ("<C-w>S", CommandFlags.None, NormalCommand.SplitViewHorizontally) yield ("<C-w><C-v>", CommandFlags.None, NormalCommand.SplitViewVertically) yield ("<C-w>v", CommandFlags.None, NormalCommand.SplitViewVertically) yield ("<C-w><C-g><C-f>", CommandFlags.None, NormalCommand.GoToFileUnderCaret true) yield ("<C-w>gf", CommandFlags.None, NormalCommand.GoToFileUnderCaret true) yield ("<C-x>", CommandFlags.Repeatable, NormalCommand.SubtractFromWord) yield ("<C-]>", CommandFlags.Special, NormalCommand.GoToDefinition) yield ("<Del>", CommandFlags.Repeatable, NormalCommand.DeleteCharacterAtCaret) yield ("<C-LeftMouse>", CommandFlags.Special, NormalCommand.GoToDefinitionUnderMouse) yield ("<C-LeftRelease>", CommandFlags.Special, NormalCommand.NoOperation) yield ("<MiddleMouse>", CommandFlags.Repeatable, NormalCommand.PutAfterCaretMouse) yield ("[p", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield ("[P", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield ("]p", CommandFlags.Repeatable, NormalCommand.PutAfterCaretWithIndent) yield ("]P", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield ("&", CommandFlags.Special, NormalCommand.RepeatLastSubstitute (false, false)) yield (".", CommandFlags.Special, NormalCommand.RepeatLastCommand) yield ("<lt><lt>", CommandFlags.Repeatable, NormalCommand.ShiftLinesLeft) yield (">>", CommandFlags.Repeatable, NormalCommand.ShiftLinesRight) yield ("==", CommandFlags.Repeatable, NormalCommand.FormatCodeLines) yield ("gx", CommandFlags.Repeatable, NormalCommand.OpenLinkUnderCaret) yield ("gqgq", CommandFlags.Repeatable, NormalCommand.FormatTextLines false) yield ("gqq", CommandFlags.Repeatable, NormalCommand.FormatTextLines false) yield ("gwgw", CommandFlags.Repeatable, NormalCommand.FormatTextLines true) yield ("gww", CommandFlags.Repeatable, NormalCommand.FormatTextLines true) yield ("!!", CommandFlags.Repeatable, NormalCommand.FilterLines) yield (":", CommandFlags.Special, NormalCommand.SwitchMode (ModeKind.Command, ModeArgument.None)) yield ("<C-^>", CommandFlags.None, NormalCommand.GoToRecentView) yield ("<LeftMouse>", CommandFlags.Special, NormalCommand.MoveCaretToMouse) yield ("<LeftDrag>", CommandFlags.Special, NormalCommand.SelectTextForMouseDrag) yield ("<LeftRelease>", CommandFlags.Special, NormalCommand.SelectTextForMouseRelease) yield ("<S-LeftMouse>", CommandFlags.Special, NormalCommand.SelectTextForMouseClick) yield ("<2-LeftMouse>", CommandFlags.Special, NormalCommand.SelectWordOrMatchingToken) yield ("<3-LeftMouse>", CommandFlags.Special, NormalCommand.SelectLine) yield ("<4-LeftMouse>", CommandFlags.Special, NormalCommand.SelectBlock) } |> Seq.map (fun (str, flags, command) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.NormalBinding (keyInputSet, flags, command)) let motionSeq = seq { yield ("c", CommandFlags.Change ||| CommandFlags.LinkedWithNextCommand ||| CommandFlags.Repeatable, NormalCommand.ChangeMotion) yield ("d", CommandFlags.Repeatable ||| CommandFlags.Delete, NormalCommand.DeleteMotion) yield ("gU", CommandFlags.Repeatable, (fun motion -> NormalCommand.ChangeCaseMotion (ChangeCharacterKind.ToUpperCase, motion))) yield ("gu", CommandFlags.Repeatable, (fun motion -> NormalCommand.ChangeCaseMotion (ChangeCharacterKind.ToLowerCase, motion))) yield ("g?", CommandFlags.Repeatable, (fun motion -> NormalCommand.ChangeCaseMotion (ChangeCharacterKind.Rot13, motion))) yield ("g~", CommandFlags.Repeatable, (fun motion -> NormalCommand.ChangeCaseMotion (ChangeCharacterKind.ToggleCase, motion))) yield ("y", CommandFlags.Yank, NormalCommand.Yank) yield ("zf", CommandFlags.None, NormalCommand.FoldMotion) yield ("<lt>", CommandFlags.Repeatable ||| CommandFlags.ShiftLeft, NormalCommand.ShiftMotionLinesLeft) yield (">", CommandFlags.Repeatable ||| CommandFlags.ShiftRight, NormalCommand.ShiftMotionLinesRight) yield ("!", CommandFlags.Repeatable, NormalCommand.FilterMotion) yield ("=", CommandFlags.Repeatable, NormalCommand.FormatCodeMotion) yield ("gq", CommandFlags.Repeatable, (fun motion -> NormalCommand.FormatTextMotion (false, motion))) yield ("gw", CommandFlags.Repeatable, (fun motion -> NormalCommand.FormatTextMotion (true, motion))) } |> Seq.map (fun (str, flags, command) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.MotionBinding (keyInputSet, flags, command)) Seq.append normalSeq motionSeq |> List.ofSeq let mutable _sharedSelectionCommands: List<CommandBinding> = List.empty let mutable _sharedSelectionCommandNameSet: Set<KeyInputSet> = Set.empty do // Up cast here to work around the F# bug which prevents accessing a CLIEvent from // a derived type let settings = _globalSettings :> IVimSettings settings.SettingChanged.Subscribe this.OnGlobalSettingsChanged |> _eventHandlers.Add member x.TextView = _vimBufferData.TextView member x.TextBuffer = _vimTextBuffer.TextBuffer member x.CaretPoint = this.TextView.Caret.Position.BufferPosition member x.IsCommandRunnerPopulated = _runner.CommandCount > 0 member x.KeyRemapMode = if _runner.IsWaitingForMoreInput then _runner.KeyRemapMode else KeyRemapMode.Normal member x.Command = _data.Command member x.Commands = this.EnsureCommands() _runner.Commands member x.CommandNames = x.EnsureCommands() _runner.Commands |> Seq.map (fun command -> command.KeyInputSet) member x.EnsureCommands() = let bindDataToStorage bindData = BindDataStorage<_>.Simple bindData /// Get a mark and us the provided 'func' to create a Motion value let bindMark func = let bindFunc (keyInput: KeyInput) = match Mark.OfChar keyInput.Char with | None -> BindResult<NormalCommand>.Error | Some localMark -> BindResult<_>.Complete (func localMark) let bindData = { KeyRemapMode = KeyRemapMode.None; BindFunction = bindFunc } bindDataToStorage bindData if not x.IsCommandRunnerPopulated then let factory = CommandFactory(_operations, _capture) _sharedSelectionCommands <- factory.CreateSelectionCommands() |> List.ofSeq _sharedSelectionCommandNameSet <- _sharedSelectionCommands |> Seq.map (fun binding -> binding.KeyInputSet) |> Set.ofSeq let complexSeq = seq { yield ("r", CommandFlags.Repeatable, x.BindReplaceChar ()) yield ("'", CommandFlags.Movement, bindMark NormalCommand.JumpToMarkLine) yield ("`", CommandFlags.Movement, bindMark NormalCommand.JumpToMark) yield ("m", CommandFlags.Special, bindDataToStorage (BindData<_>.CreateForChar KeyRemapMode.None NormalCommand.SetMarkToCaret)) yield ("@", CommandFlags.Special, bindDataToStorage (BindData<_>.CreateForChar KeyRemapMode.None NormalCommand.RunAtCommand)) } |> Seq.map (fun (str, flags, storage) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.ComplexNormalBinding (keyInputSet, flags, storage)) SharedStandardCommands |> Seq.append complexSeq |> Seq.append (factory.CreateMovementCommands()) |> Seq.append (factory.CreateScrollCommands()) |> Seq.iter _runner.Add // Add in the special ~ command let _, command = x.GetTildeCommand() _runner.Add command // Add in the macro command factory.CreateMacroEditCommands _runner _vimTextBuffer.Vim.MacroRecorder _eventHandlers // Save the alternate selection command bindings _selectionAlternateCommands <- _runner.Commands |> Seq.filter (fun commandBinding -> Set.contains commandBinding.KeyInputSet _sharedSelectionCommandNameSet) |> List.ofSeq // The command list is built without selection commands. If selection is enabled go // ahead and switch over now if Util.IsFlagSet _globalSettings.KeyModelOptions KeyModelOptions.StartSelection then x.UpdateSelectionCommands() /// Raised when a global setting is changed member x.OnGlobalSettingsChanged (args: SettingEventArgs) = if x.IsCommandRunnerPopulated then let setting = args.Setting if StringUtil.IsEqual setting.Name GlobalSettingNames.TildeOpName then x.UpdateTildeCommand() elif StringUtil.IsEqual setting.Name GlobalSettingNames.KeyModelName then x.UpdateSelectionCommands() /// Bind the character in a replace character command: 'r'. member x.BindReplaceChar () = let func () = _data <- { _data with InReplace = true } let bindFunc (keyInput: KeyInput) = _data <- { _data with InReplace = false } match keyInput.Key with | VimKey.Escape -> BindResult.Cancelled | VimKey.Back -> BindResult.Cancelled | VimKey.Delete -> BindResult.Cancelled | _ -> NormalCommand.ReplaceChar keyInput |> BindResult.Complete { KeyRemapMode = KeyRemapMode.Language; BindFunction = bindFunc } BindDataStorage.Complex func /// Get the information on how to handle the tilde command based on the current setting for 'tildeop' member x.GetTildeCommand() = let name = KeyInputUtil.CharToKeyInput '~' |> KeyInputSetUtil.Single let flags = CommandFlags.Repeatable let command = if _globalSettings.TildeOp then CommandBinding.MotionBinding (name, flags, (fun motion -> NormalCommand.ChangeCaseMotion (ChangeCharacterKind.ToggleCase, motion))) else CommandBinding.NormalBinding (name, flags, NormalCommand.ChangeCaseCaretPoint ChangeCharacterKind.ToggleCase) name, command /// Ensure that the correct commands are loaded for the selection KeyInput values member x.UpdateSelectionCommands() = // Remove all of the commands with that binding _sharedSelectionCommandNameSet |> Seq.iter _runner.Remove let commandList = if Util.IsFlagSet _globalSettings.KeyModelOptions KeyModelOptions.StartSelection then _sharedSelectionCommands else _selectionAlternateCommands commandList |> List.iter _runner.Add member x.UpdateTildeCommand() = let name, command = x.GetTildeCommand() _runner.Remove name _runner.Add command /// Create the CommandBinding instances for the supported NormalCommand values member x.Reset() = _runner.ResetState() _data <- EmptyData member x.CanProcess (keyInput: KeyInput) = KeyInputUtil.IsCore keyInput && not keyInput.IsMouseKey || _runner.DoesCommandStartWith keyInput + || x.KeyRemapMode = KeyRemapMode.Language && KeyInputUtil.IsTextInput keyInput member x.Process (keyInputData: KeyInputData) = // Update the text of the command so long as this isn't a control character let keyInput = keyInputData.KeyInput if not (CharUtil.IsControl keyInput.Char) then let command = _data.Command + keyInput.Char.ToString() _data <- { _data with Command = command } match _runner.Run keyInput with | BindResult.NeedMoreInput _ -> ProcessResult.HandledNeedMoreInput | BindResult.Complete commandData -> x.Reset() ProcessResult.OfCommandResult commandData.CommandResult | BindResult.Error -> x.Reset() ProcessResult.NotHandled | BindResult.Cancelled -> _incrementalSearch.CancelSession() x.Reset() ProcessResult.Handled ModeSwitch.NoSwitch member x.OnEnter (arg: ModeArgument) = x.EnsureCommands() x.Reset() // Ensure the caret is positioned correctly vis a vis virtual edit if not _textView.IsClosed && not (TextViewUtil.GetCaretPoint(_textView).Position = 0) then _operations.EnsureAtCaret ViewFlags.VirtualEdit // Process the argument if it's applicable arg.CompleteAnyTransaction interface INormalMode with member x.KeyRemapMode = x.KeyRemapMode member x.InCount = _runner.InCount member x.InReplace = _data.InReplace member x.VimTextBuffer = _vimTextBuffer member x.Command = x.Command member x.CommandRunner = _runner member x.CommandNames = x.CommandNames member x.ModeKind = ModeKind.Normal member x.CanProcess keyInput = x.CanProcess keyInput member x.Process keyInputData = x.Process keyInputData member x.OnEnter arg = x.OnEnter arg member x.OnLeave () = () member x.OnClose() = _eventHandlers.DisposeAll() diff --git a/Src/VimCore/Modes_Visual_VisualMode.fs b/Src/VimCore/Modes_Visual_VisualMode.fs index 68f79d7..8327fc0 100644 --- a/Src/VimCore/Modes_Visual_VisualMode.fs +++ b/Src/VimCore/Modes_Visual_VisualMode.fs @@ -1,340 +1,341 @@ #light namespace Vim.Modes.Visual open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Operations open Microsoft.VisualStudio.Text.Editor open Vim open Vim.Modes type internal VisualMode ( _vimBufferData: IVimBufferData, _operations: ICommonOperations, _motionUtil: IMotionUtil, _visualKind: VisualKind, _runner: ICommandRunner, _capture: IMotionCapture, _selectionTracker: ISelectionTracker ) = let _vimTextBuffer = _vimBufferData.VimTextBuffer let _textView = _vimBufferData.TextView let _textBuffer = _vimTextBuffer.TextBuffer let _globalSettings = _vimTextBuffer.GlobalSettings let _eventHandlers = DisposableBag() let _operationKind, _modeKind = match _visualKind with | VisualKind.Character -> (OperationKind.CharacterWise, ModeKind.VisualCharacter) | VisualKind.Line -> (OperationKind.LineWise, ModeKind.VisualLine) | VisualKind.Block -> (OperationKind.CharacterWise, ModeKind.VisualBlock) // Command to show when entering command from Visual Mode static let CommandFromVisualModeString = "'<,'>" /// Get a mark and use the provided 'func' to create a Motion value static let BindMark func = let bindFunc (keyInput: KeyInput) = match Mark.OfChar keyInput.Char with | None -> BindResult<NormalCommand>.Error | Some localMark -> BindResult<_>.Complete (func localMark) let bindData = { KeyRemapMode = KeyRemapMode.None BindFunction = bindFunc } BindDataStorage<_>.Simple bindData static let SharedCommands = let visualSeq = seq { yield ("c", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeSelection) yield ("C", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeLineSelection true) yield ("d", CommandFlags.Repeatable, VisualCommand.DeleteSelection) yield ("D", CommandFlags.Repeatable, VisualCommand.DeleteLineSelection) yield ("gf", CommandFlags.None, VisualCommand.GoToFileInSelection) yield ("gJ", CommandFlags.Repeatable, VisualCommand.JoinSelection JoinKind.KeepEmptySpaces) yield ("gp", CommandFlags.Repeatable, VisualCommand.PutOverSelection true) yield ("gP", CommandFlags.Repeatable, VisualCommand.PutOverSelection true) yield ("g?", CommandFlags.Repeatable, VisualCommand.ChangeCase ChangeCharacterKind.Rot13) yield ("gn", CommandFlags.Repeatable, VisualCommand.ExtendSelectionToNextMatch SearchPath.Forward) yield ("gN", CommandFlags.Repeatable, VisualCommand.ExtendSelectionToNextMatch SearchPath.Backward) yield ("J", CommandFlags.Repeatable, VisualCommand.JoinSelection JoinKind.RemoveEmptySpaces) yield ("o", CommandFlags.Movement ||| CommandFlags.ResetAnchorPoint, VisualCommand.InvertSelection false) yield ("O", CommandFlags.Movement ||| CommandFlags.ResetAnchorPoint, VisualCommand.InvertSelection true) yield ("p", CommandFlags.Repeatable, VisualCommand.PutOverSelection false) yield ("P", CommandFlags.Repeatable, VisualCommand.PutOverSelection false) yield ("R", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeLineSelection false) yield ("s", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeSelection) yield ("S", CommandFlags.Repeatable ||| CommandFlags.LinkedWithNextCommand, VisualCommand.ChangeLineSelection false) yield ("u", CommandFlags.Repeatable, VisualCommand.ChangeCase ChangeCharacterKind.ToLowerCase) yield ("U", CommandFlags.Repeatable, VisualCommand.ChangeCase ChangeCharacterKind.ToUpperCase) yield ("v", CommandFlags.Special, VisualCommand.SwitchModeVisual VisualKind.Character) yield ("V", CommandFlags.Special, VisualCommand.SwitchModeVisual VisualKind.Line) yield ("x", CommandFlags.Repeatable, VisualCommand.DeleteSelection) yield ("X", CommandFlags.Repeatable, VisualCommand.DeleteLineSelection) yield ("y", CommandFlags.ResetCaret, VisualCommand.YankSelection) yield ("Y", CommandFlags.ResetCaret, VisualCommand.YankLineSelection) yield ("zf", CommandFlags.None, VisualCommand.FoldSelection) yield ("zF", CommandFlags.None, VisualCommand.FoldSelection) yield ("zo", CommandFlags.Special, VisualCommand.OpenFoldInSelection) yield ("zO", CommandFlags.Special, VisualCommand.OpenAllFoldsInSelection) yield ("zc", CommandFlags.Special, VisualCommand.CloseFoldInSelection) yield ("zC", CommandFlags.Special, VisualCommand.CloseAllFoldsInSelection) yield ("za", CommandFlags.Special, VisualCommand.ToggleFoldInSelection) yield ("zA", CommandFlags.Special, VisualCommand.ToggleAllFoldsInSelection) yield ("zd", CommandFlags.Special, VisualCommand.DeleteAllFoldsInSelection) yield ("zD", CommandFlags.Special, VisualCommand.DeleteAllFoldsInSelection) yield ("<C-c>", CommandFlags.Special, VisualCommand.CancelOperation) yield ("<C-q>", CommandFlags.Special, VisualCommand.SwitchModeVisual VisualKind.Block) yield ("<C-v>", CommandFlags.Special, VisualCommand.SwitchModeVisual VisualKind.Block) yield ("<S-i>", CommandFlags.Special, VisualCommand.SwitchModeInsert VisualInsertKind.Start) yield ("<S-a>", CommandFlags.Special, VisualCommand.SwitchModeInsert VisualInsertKind.End) yield ("<C-g>", CommandFlags.Special, VisualCommand.SwitchModeOtherVisual) yield ("<C-w>gf", CommandFlags.None, VisualCommand.GoToFileInSelectionInNewWindow) yield ("<Del>", CommandFlags.Repeatable, VisualCommand.DeleteSelection) yield ("<lt>", CommandFlags.Repeatable, VisualCommand.ShiftLinesLeft) yield (">", CommandFlags.Repeatable, VisualCommand.ShiftLinesRight) yield ("~", CommandFlags.Repeatable, VisualCommand.ChangeCase ChangeCharacterKind.ToggleCase) yield ("=", CommandFlags.Repeatable, VisualCommand.FormatCodeLines) yield ("gq", CommandFlags.Repeatable, VisualCommand.FormatTextLines false) yield ("gw", CommandFlags.Repeatable, VisualCommand.FormatTextLines true) yield ("gx", CommandFlags.Repeatable, VisualCommand.OpenLinkInSelection) yield ("!", CommandFlags.Repeatable, VisualCommand.FilterLines) yield ("<C-a>", CommandFlags.Repeatable, VisualCommand.AddToSelection false) yield ("<C-x>", CommandFlags.Repeatable, VisualCommand.SubtractFromSelection false) yield ("g<C-a>", CommandFlags.Repeatable, VisualCommand.AddToSelection true) yield ("g<C-x>", CommandFlags.Repeatable, VisualCommand.SubtractFromSelection true) yield ("<LeftMouse>", CommandFlags.Special, VisualCommand.MoveCaretToMouse) yield ("<LeftDrag>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseDrag) yield ("<LeftRelease>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseRelease) yield ("<S-LeftMouse>", CommandFlags.Special, VisualCommand.ExtendSelectionForMouseClick) yield ("<2-LeftMouse>", CommandFlags.Special, VisualCommand.SelectWordOrMatchingToken) yield ("<3-LeftMouse>", CommandFlags.Special, VisualCommand.SelectLine) yield ("<4-LeftMouse>", CommandFlags.Special, VisualCommand.SelectBlock) } |> Seq.map (fun (str, flags, command) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.VisualBinding (keyInputSet, flags, command)) let complexSeq = seq { - yield ("r", CommandFlags.Repeatable, BindData<_>.CreateForKeyInput KeyRemapMode.None VisualCommand.ReplaceSelection) + yield ("r", CommandFlags.Repeatable, BindData<_>.CreateForKeyInput KeyRemapMode.Language VisualCommand.ReplaceSelection) } |> Seq.map (fun (str, flags, bindCommand) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str let storage = BindDataStorage.Simple bindCommand CommandBinding.ComplexVisualBinding (keyInputSet, flags, storage)) let normalSeq = seq { yield ("gv", CommandFlags.Special, NormalCommand.SwitchPreviousVisualMode) yield ("zE", CommandFlags.Special, NormalCommand.DeleteAllFoldsInBuffer) yield ("zM", CommandFlags.Special, NormalCommand.CloseAllFolds) yield ("zR", CommandFlags.Special, NormalCommand.OpenAllFolds) yield ("[p", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield ("[P", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield ("]p", CommandFlags.Repeatable, NormalCommand.PutAfterCaretWithIndent) yield ("]P", CommandFlags.Repeatable, NormalCommand.PutBeforeCaretWithIndent) yield (":", CommandFlags.Special, NormalCommand.SwitchMode (ModeKind.Command, (ModeArgument.PartialCommand CommandFromVisualModeString))) } |> Seq.map (fun (str, flags, command) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.NormalBinding (keyInputSet, flags, command)) let normalComplexSeq = seq { yield ("'", CommandFlags.Movement, BindMark NormalCommand.JumpToMarkLine) yield ("`", CommandFlags.Movement, BindMark NormalCommand.JumpToMark) } |> Seq.map (fun (str, flags, storage) -> let keyInputSet = KeyNotationUtil.StringToKeyInputSet str CommandBinding.ComplexNormalBinding (keyInputSet, flags, storage)) Seq.append visualSeq complexSeq |> Seq.append normalSeq |> Seq.append normalComplexSeq |> List.ofSeq let mutable _builtCommands = false member x.CurrentSnapshot = _textBuffer.CurrentSnapshot member x.CaretPoint = TextViewUtil.GetCaretPoint _textView member x.CanProcess (keyInput: KeyInput) = KeyInputUtil.IsCore keyInput && not keyInput.IsMouseKey ||_runner.DoesCommandStartWith keyInput + || x.KeyRemapMode = KeyRemapMode.Language && KeyInputUtil.IsTextInput keyInput member x.CommandNames = x.EnsureCommandsBuilt() _runner.Commands |> Seq.map (fun command -> command.KeyInputSet) member this.KeyRemapMode = if _runner.IsWaitingForMoreInput then _runner.KeyRemapMode else KeyRemapMode.Visual member x.SelectedSpan = (TextSelectionUtil.GetStreamSelectionSpan _textView.Selection).SnapshotSpan member x.EnsureCommandsBuilt() = if not _builtCommands then let factory = CommandFactory(_operations, _capture) // Add in the standard commands factory.CreateMovementCommands() |> Seq.append (factory.CreateMovementTextObjectCommands()) |> Seq.append (factory.CreateScrollCommands()) |> Seq.append SharedCommands |> Seq.iter _runner.Add // Add in macro editing factory.CreateMacroEditCommands _runner _vimTextBuffer.Vim.MacroRecorder _eventHandlers _builtCommands <- true member x.OnEnter modeArgument = x.EnsureCommandsBuilt() _selectionTracker.RecordCaretTrackingPoint modeArgument _selectionTracker.Start() member x.OnClose() = _eventHandlers.DisposeAll() /// Called when the Visual Mode is left. Need to update the LastVisualSpan based on our selection member x.OnLeave() = _runner.ResetState() _selectionTracker.Stop() /// The current Visual Selection member x.VisualSelection = let selectionKind = _globalSettings.SelectionKind let tabStop = _vimBufferData.LocalSettings.TabStop let useVirtualSpace = _vimTextBuffer.UseVirtualSpace let visualSelection = VisualSelection.CreateForVirtualSelection _textView _visualKind selectionKind tabStop useVirtualSpace let isMaintainingEndOfLine = _vimBufferData.MaintainCaretColumn.IsMaintainingEndOfLine visualSelection.AdjustWithEndOfLine isMaintainingEndOfLine member x.Process (keyInputData: KeyInputData) = let keyInput = keyInputData.KeyInput // Save the last visual selection at the global level for use with [count]V|v except // in the case of <Esc>. This <Esc> exception is not a documented behavior but exists // experimentally. match keyInput, _vimTextBuffer.LastVisualSelection with | keyInput, Some lastVisualSelection when keyInput <> KeyInputUtil.EscapeKey -> let vimData = _vimBufferData.Vim.VimData match StoredVisualSelection.CreateFromVisualSpan lastVisualSelection.VisualSpan with | None -> () | Some v -> vimData.LastVisualSelection <- Some v | _ -> () let result = if keyInput = KeyInputUtil.EscapeKey && x.ShouldHandleEscape then ProcessResult.Handled ModeSwitch.SwitchPreviousMode else match _runner.Run keyInput with | BindResult.NeedMoreInput _ -> _selectionTracker.UpdateSelection() ProcessResult.HandledNeedMoreInput | BindResult.Complete commandRanData -> if Util.IsFlagSet commandRanData.CommandBinding.CommandFlags CommandFlags.ResetCaret then x.ResetCaret() if Util.IsFlagSet commandRanData.CommandBinding.CommandFlags CommandFlags.ResetAnchorPoint then match _vimBufferData.VisualAnchorPoint |> OptionUtil.map2 (TrackingPointUtil.GetPoint x.CurrentSnapshot) with | None -> () | Some anchorPoint -> let anchorPoint = VirtualSnapshotPointUtil.OfPoint anchorPoint _selectionTracker.UpdateSelectionWithAnchorPoint anchorPoint match commandRanData.CommandResult with | CommandResult.Error -> _selectionTracker.UpdateSelection() | CommandResult.Completed modeSwitch -> match modeSwitch with | ModeSwitch.NoSwitch -> _selectionTracker.UpdateSelection() | ModeSwitch.SwitchMode(_) -> () | ModeSwitch.SwitchModeWithArgument(_,_) -> () | ModeSwitch.SwitchPreviousMode -> () | ModeSwitch.SwitchModeOneTimeCommand _ -> () ProcessResult.OfCommandResult commandRanData.CommandResult | BindResult.Error -> _selectionTracker.UpdateSelection() _operations.Beep() if keyInput.IsMouseKey then ProcessResult.NotHandled else ProcessResult.Handled ModeSwitch.NoSwitch | BindResult.Cancelled -> _selectionTracker.UpdateSelection() ProcessResult.Handled ModeSwitch.NoSwitch // If we are switching out Visual Mode then reset the selection. Only do this if // we are the active IMode. It's very possible that we were switched out already // as part of a complex command if result.IsAnySwitch && _selectionTracker.IsRunning then // On teardown we will get calls to Stop when the view is closed. It's invalid to access // the selection at that point if not _textView.IsClosed then if result.IsAnySwitchToVisual then _selectionTracker.UpdateSelection() elif not result.IsAnySwitchToCommand then _textView.Selection.Clear() _textView.Selection.Mode <- TextSelectionMode.Stream result /// Certain operations cause the caret to be reset to it's position before visual mode /// started once visual mode is complete (y for example). This function handles that member x.ResetCaret() = // Calculate the start point of the selection let startPoint = match _vimBufferData.VisualCaretStartPoint with | None -> None | Some trackingPoint -> TrackingPointUtil.GetPoint x.CurrentSnapshot trackingPoint match startPoint with | None -> // If we couldn't calculate a start point then there is just nothing to do. This // really shouldn't happen though () | Some startPoint -> // Calculate the actual point to use. If the selection turned backwards then we // prefer the current caret over the original let point = if startPoint.Position < x.CaretPoint.Position then startPoint else x.CaretPoint _operations.MoveCaretToPoint point ViewFlags.Standard member x.ShouldHandleEscape = not _runner.IsHandlingEscape member x.SyncSelection() = if _selectionTracker.IsRunning then _selectionTracker.Stop() _selectionTracker.Start() interface IMode with member x.VimTextBuffer = _vimTextBuffer member x.CommandNames = x.CommandNames member x.ModeKind = _modeKind member x.CanProcess keyInput = x.CanProcess keyInput member x.Process keyInputData = x.Process keyInputData member x.OnEnter modeArgument = x.OnEnter modeArgument member x.OnLeave () = x.OnLeave() member x.OnClose() = x.OnClose() interface IVisualMode with member x.CommandRunner = _runner member x.KeyRemapMode = x.KeyRemapMode member x.InCount = _runner.InCount member x.VisualSelection = x.VisualSelection member x.SyncSelection () = x.SyncSelection() diff --git a/Test/VimCoreTest/NormalModeIntegrationTest.cs b/Test/VimCoreTest/NormalModeIntegrationTest.cs index 8400790..d51242d 100644 --- a/Test/VimCoreTest/NormalModeIntegrationTest.cs +++ b/Test/VimCoreTest/NormalModeIntegrationTest.cs @@ -6125,1024 +6125,1036 @@ namespace Vim.UnitTest _vimBuffer.Process(KeyInputUtil.EscapeKey); _vimBuffer.Process(VimKey.Down); _vimBuffer.Process("."); Assert.Equal("ar", _textView.GetLine(0).GetText()); Assert.Equal("g", _textView.GetLine(1).GetText()); } [WpfFact] public void Change2() { Create("bear", "dog", "cat", "zebra", "fox", "jazz"); _vimBuffer.Process("cl"); _vimBuffer.Process("u"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _vimBuffer.Process(VimKey.Down); _vimBuffer.Process("."); Assert.Equal("uear", _textView.GetLine(0).GetText()); Assert.Equal("uog", _textView.GetLine(1).GetText()); } [WpfFact] public void Substitute1() { Create("bear", "dog", "cat", "zebra", "fox", "jazz"); _vimBuffer.Process("s"); _vimBuffer.Process("u"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _vimBuffer.Process(VimKey.Down); _vimBuffer.Process("."); Assert.Equal("uear", _textView.GetLine(0).GetText()); Assert.Equal("uog", _textView.GetLine(1).GetText()); } [WpfFact] public void Substitute2() { Create("bear", "dog", "cat", "zebra", "fox", "jazz"); _vimBuffer.Process("s"); _vimBuffer.Process("u"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _vimBuffer.Process(VimKey.Down); _vimBuffer.Process("2."); Assert.Equal("uear", _textView.GetLine(0).GetText()); Assert.Equal("ug", _textView.GetLine(1).GetText()); } [WpfFact] public void TextInsert1() { Create("bear", "dog", "cat", "zebra", "fox", "jazz"); _vimBuffer.Process("i"); _vimBuffer.Process("abc"); _vimBuffer.Process(KeyInputUtil.EscapeKey); Assert.Equal(2, _textView.GetCaretPoint().Position); _vimBuffer.Process("."); Assert.Equal("ababccbear", _textView.GetLine(0).GetText()); } [WpfFact] public void TextInsert2() { Create("bear", "dog", "cat", "zebra", "fox", "jazz"); _vimBuffer.Process("i"); _vimBuffer.Process("abc"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _textView.MoveCaretTo(0); _vimBuffer.Process("."); Assert.Equal("abcabcbear", _textView.GetLine(0).GetText()); Assert.Equal(2, _textView.GetCaretPoint().Position); } [WpfFact] public void TextInsert3() { Create("bear", "dog", "cat", "zebra", "fox", "jazz"); _vimBuffer.Process("i"); _vimBuffer.Process("abc"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _textView.MoveCaretTo(0); _vimBuffer.Process("."); _vimBuffer.Process("."); Assert.Equal("ababccabcbear", _textView.GetLine(0).GetText()); } /// <summary> /// Repeating an insert with a new count applies the count to the /// insertion /// </summary> [WpfFact] public void RepeatInsertWithNewCount() { // Reported in issue #2259. Create("cat", ""); _vimBuffer.Process("i"); _vimBuffer.Process("dog "); _vimBuffer.Process(KeyInputUtil.EscapeKey); Assert.Equal("dog cat", _textView.GetLine(0).GetText()); _textView.MoveCaretTo(0); _vimBuffer.Process("2."); Assert.Equal("dog dog dog cat", _textView.GetLine(0).GetText()); Assert.Equal(7, _textView.GetCaretPoint().Position); } /// <summary> /// Test the repeating of a command that changes white space to tabs /// </summary> [WpfFact] public void TextInsert_WhiteSpaceToTab() { Create(" hello world", "dog"); _vimBuffer.LocalSettings.TabStop = 4; _vimBuffer.LocalSettings.ExpandTab = false; _vimBuffer.Process('i'); _textBuffer.Replace(new Span(0, 4), "\t\t"); _vimBuffer.Process(VimKey.Escape); _textView.MoveCaretToLine(1); _vimBuffer.Process('.'); Assert.Equal("\tdog", _textView.GetLine(1).GetText()); } /// <summary> /// The first repeat of I should go to the first non-blank /// </summary> [WpfFact] public void CapitalI1() { Create("bear", "dog", "cat", "zebra", "fox", "jazz"); _vimBuffer.Process("I"); _vimBuffer.Process("abc"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _textView.MoveCaretTo(_textView.GetLine(1).Start.Add(2)); _vimBuffer.Process("."); Assert.Equal("abcdog", _textView.GetLine(1).GetText()); Assert.Equal(_textView.GetLine(1).Start.Add(2), _textView.GetCaretPoint()); } /// <summary> /// The first repeat of I should go to the first non-blank /// </summary> [WpfFact] public void CapitalI2() { Create("bear", " dog", "cat", "zebra", "fox", "jazz"); _vimBuffer.Process("I"); _vimBuffer.Process("abc"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _textView.MoveCaretTo(_textView.GetLine(1).Start.Add(2)); _vimBuffer.Process("."); Assert.Equal(" abcdog", _textView.GetLine(1).GetText()); Assert.Equal(_textView.GetLine(1).Start.Add(4), _textView.GetCaretPoint()); } /// <summary> /// Repeating a /// replace char command from visual mode should not move the caret /// </summary> [WpfFact] public void ReplaceCharVisual_ShouldNotMoveCaret() { Create("the dog kicked the ball"); _vimBuffer.VimData.LastCommand = FSharpOption.Create(StoredCommand.NewVisualCommand( VisualCommand.NewReplaceSelection(KeyInputUtil.CharToKeyInput('b')), VimUtil.CreateCommandData(), StoredVisualSpan.OfVisualSpan(VimUtil.CreateVisualSpanCharacter(_textView.GetLineSpan(0, 3))), CommandFlags.None)); _textView.MoveCaretTo(1); _vimBuffer.Process("."); Assert.Equal("tbbbdog kicked the ball", _textView.GetLine(0).GetText()); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// Make sure the caret movement occurs as part of the repeat /// </summary> [WpfFact] public void AppendShouldRepeat() { Create("{", "}"); _textView.MoveCaretToLine(0); _vimBuffer.Process('a'); _vimBuffer.Process(';'); _vimBuffer.Process(VimKey.Escape); _textView.MoveCaretToLine(1); _vimBuffer.Process('.'); Assert.Equal("};", _textView.GetLine(1).GetText()); } /// <summary> /// Make sure the caret movement occurs as part of the repeat /// </summary> [WpfFact] public void AppendEndOfLineShouldRepeat() { Create("{", "}"); _textView.MoveCaretToLine(0); _vimBuffer.Process('A'); _vimBuffer.Process(';'); _vimBuffer.Process(VimKey.Escape); _textView.MoveCaretToLine(1); _vimBuffer.Process('.'); Assert.Equal("};", _textView.GetLine(1).GetText()); } /// <summary> /// A simple insert line above should be undone all at once /// </summary> [WpfFact] public void UndoInsertLineAbove() { Create("cat", "dog", "tree"); _textView.MoveCaretToLine(2); _vimBuffer.Process("O fish"); _vimBuffer.Process(VimKey.Escape); Assert.Equal(new[] { "cat", "dog", " fish", "tree" }, _textBuffer.GetLines()); _vimBuffer.Process("u"); Assert.Equal(new[] { "cat", "dog", "tree" }, _textBuffer.GetLines()); } /// <summary> /// A simple insert line below should be undone all at once /// </summary> [WpfFact] public void UndoInsertLineBelow() { Create("cat", "dog", "tree"); _vimBuffer.Process("o fish"); _vimBuffer.Process(VimKey.Escape); Assert.Equal(new[] { "cat", " fish", "dog", "tree" }, _textBuffer.GetLines()); _vimBuffer.Process("u"); Assert.Equal(new[] { "cat", "dog", "tree" }, _textBuffer.GetLines()); } /// <summary> /// The insert line above command should be linked the the following text change /// </summary> [WpfFact] public void InsertLineAbove() { Create("cat", "dog", "tree"); _textView.MoveCaretToLine(2); _vimBuffer.Process("O fish"); _vimBuffer.Process(VimKey.Escape); Assert.Equal(" fish", _textView.GetLine(2).GetText()); _textView.MoveCaretToLine(1); _vimBuffer.Process("."); Assert.Equal(" fish", _textView.GetLine(1).GetText()); } /// <summary> /// The insert line below command should be linked the the following text change /// </summary> [WpfFact] public void InsertLineBelow() { Create("cat", "dog", "tree"); _vimBuffer.Process("o fish"); _vimBuffer.Process(VimKey.Escape); Assert.Equal(" fish", _textView.GetLine(1).GetText()); _textView.MoveCaretToLine(2); _vimBuffer.Process("."); Assert.Equal(" fish", _textView.GetLine(3).GetText()); } /// <summary> /// The 'o' command used to have a bug which occured when /// /// - Insert mode made no edits /// - The 'o' command put the caret into virtual space /// /// In that case the next edit command would link with the insert line below /// change in the repeat infrastructure. Normally the move caret left /// operation processed on Escape moved the caret and ended a repeat. But /// the move left from virtual space didn't use a proper command and /// caused repeat to remain open /// /// Regression Test for Issue #748 /// </summary> [WpfFact] public void InsertLineBelow_ToVirtualSpace() { Create("cat", "dog"); _vimBuffer.Process('o'); _textView.MoveCaretTo(_textView.GetCaretPoint().Position, 4); _vimBuffer.Process(VimKey.Escape); _textView.MoveCaretTo(0); _vimBuffer.ProcessNotation("cwbear<Esc>"); _textView.MoveCaretToLine(2); _vimBuffer.Process('.'); Assert.Equal("bear", _textBuffer.GetLine(2).GetText()); } [WpfFact] public void DeleteWithIncrementalSearch() { Create("dog cat bear tree"); _vimBuffer.Process("d/a", enter: true); _vimBuffer.Process('.'); Assert.Equal("ar tree", _textView.GetLine(0).GetText()); } /// <summary> /// Test the repeat of a repeated command. Essentially ensure the act of repeating doesn't /// disturb the cached LastCommand value /// </summary> [WpfFact] public void Repeated() { Create("the fox chased the bird"); _vimBuffer.Process("dw"); Assert.Equal("fox chased the bird", _textView.TextSnapshot.GetText()); _vimBuffer.Process("."); Assert.Equal("chased the bird", _textView.TextSnapshot.GetText()); _vimBuffer.Process("."); Assert.Equal("the bird", _textView.TextSnapshot.GetText()); } [WpfFact] public void LinkedTextChange1() { Create("the fox chased the bird"); _vimBuffer.Process("cw"); _vimBuffer.Process("hey "); _vimBuffer.Process(KeyInputUtil.EscapeKey); _textView.MoveCaretTo(4); _vimBuffer.Process(KeyInputUtil.CharToKeyInput('.')); Assert.Equal("hey hey fox chased the bird", _textView.TextSnapshot.GetText()); } [WpfFact] public void LinkedTextChange2() { Create("the fox chased the bird"); _vimBuffer.Process("cw"); _vimBuffer.Process("hey"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _textView.MoveCaretTo(4); _vimBuffer.Process(KeyInputUtil.CharToKeyInput('.')); Assert.Equal("hey hey chased the bird", _textView.TextSnapshot.GetText()); } [WpfFact] public void LinkedTextChange3() { Create("the fox chased the bird"); _vimBuffer.Process("cw"); _vimBuffer.Process("hey"); _vimBuffer.Process(KeyInputUtil.EscapeKey); _textView.MoveCaretTo(4); _vimBuffer.Process(KeyInputUtil.CharToKeyInput('.')); _vimBuffer.Process(KeyInputUtil.CharToKeyInput('.')); Assert.Equal("hey hehey chased the bird", _textView.TextSnapshot.GetText()); } /// <summary> /// Make sure the undo layer doesn't flag an empty repeat as an error. It is always /// possible for a repeat to fail /// </summary> [WpfFact] public void EmptyCommand() { Create("cat", "dog"); _vimBuffer.ProcessNotation("ctablah<Esc>"); _textView.MoveCaretToLine(1); _vimBuffer.ProcessNotation("."); } /// <summary> /// The count passed into . should replace the count originally provided to the motion. /// </summary> [WpfFact] public void CountReplacesOperatorCount() { Create("cat dog fish tree", "cat dog fish tree"); _vimBuffer.Process("d2w"); Assert.Equal("fish tree", _textBuffer.GetLine(0).GetText()); _textView.MoveCaretToLine(1); _vimBuffer.Process("3."); Assert.Equal("tree", _textBuffer.GetLine(1).GetText()); } /// <summary> /// The count passed into . should replace the count originally provided to the operator. /// </summary> [WpfFact] public void CountReplacesMotionCount() { Create("cat dog fish tree", "cat dog fish tree"); _vimBuffer.Process("2dw"); Assert.Equal("fish tree", _textBuffer.GetLine(0).GetText()); _textView.MoveCaretToLine(1); _vimBuffer.Process("3."); Assert.Equal("tree", _textBuffer.GetLine(1).GetText()); } /// <summary> /// The count passed into . should replace the count originally provided to the operator and /// motion. /// </summary> [WpfFact] public void CountReplacesOperatoraAndMotionCount() { Create("cat dog fish tree", "cat dog fish tree"); _vimBuffer.Process("2d2w"); Assert.Equal("", _textBuffer.GetLine(0).GetText()); _textView.MoveCaretToLine(1); _vimBuffer.Process("3."); Assert.Equal("tree", _textBuffer.GetLine(1).GetText()); } } public sealed class ReplaceCharTest : NormalModeIntegrationTest { [WpfFact] public void Simple() { Create("cat dog"); _vimBuffer.Process("rb"); Assert.Equal("bat dog", _textBuffer.GetLine(0).GetText()); Assert.Equal(0, _textView.GetCaretPoint()); } /// <summary> /// When there is a count involved the caret should be positioned on the final character /// that is relpaced /// </summary> [WpfFact] public void WithCount() { Create("cat dog"); _vimBuffer.Process("3ro"); Assert.Equal("ooo dog", _textBuffer.GetLine(0).GetText()); Assert.Equal(2, _textView.GetCaretPoint()); } /// <summary> /// When the count exceeds the length of the line then no change should occur and a beep /// should be raised /// </summary> [WpfFact] public void CountTooBig() { Create("cat", "dog fish tree"); _vimBuffer.Process("10ro"); Assert.Equal(1, VimHost.BeepCount); Assert.Equal("cat", _textBuffer.GetLine(0).GetText()); } /// <summary> /// There is no known extension which does this yet but it is possible for a subsequent change /// to delete the buffer up to the position that we want to move the caret to. Must account /// for that by simply not crashing. Move to the best possible position /// </summary> [WpfFact] public void AfterChangeDeleteTargetCaretPosition() { Create("cat dog"); _textView.MoveCaretTo(5); var first = true; _textBuffer.Changed += delegate { if (first) { first = false; _textBuffer.Replace(new Span(0, 7), "at"); } }; _vimBuffer.Process("r2"); Assert.Equal("at", _textBuffer.GetLine(0).GetText()); Assert.Equal(2, _textView.GetCaretPoint()); } /// <summary> /// In Vs 2012 if you change a tag name with a simple relpace it will change the matching /// tag with a subsequent edit. This means the ITextSnapshot which returns from the replace /// will be a version behind the current version of the ITextView. Need to make sure we /// use the correct ITextSnapshot for the caret positioning /// </summary> [WpfFact] public void Issue1040() { Create("<h1>test</h1>"); _textView.MoveCaretTo(2); var first = true; _textBuffer.Changed += delegate { if (first) { first = false; _textBuffer.Replace(new Span(11, 1), "2"); } }; _vimBuffer.Process("r2"); Assert.Equal("<h2>test</h2>", _textBuffer.GetLine(0).GetText()); Assert.Equal(2, _textView.GetCaretPoint()); } /// <summary> /// When the replace character is a new line we need to respect the line ending of the current /// line when inserting the text /// </summary> [WpfFact] public void Issue1198() { Create(""); _textBuffer.SetText("cat\ndog"); _textView.MoveCaretTo(0); Assert.Equal("\n", _textBuffer.GetLine(0).GetLineBreakText()); _vimBuffer.ProcessNotation("r<Enter>"); Assert.Equal("\n", _textBuffer.GetLine(0).GetLineBreakText()); Assert.Equal("", _textBuffer.GetLine(0).GetText()); } + + [WpfFact] + public void ReplaceNonAscii() + { + // Reported in issue #2702. + Create("abc", ""); + Assert.False(_vimBuffer.CanProcess(KeyInputUtil.CharToKeyInput('©'))); + _vimBuffer.Process("r"); + Assert.True(_vimBuffer.CanProcess(KeyInputUtil.CharToKeyInput('©'))); + _vimBuffer.Process("©"); + Assert.Equal(new[] { "©bc", "" }, _textBuffer.GetLines()); + } } public abstract class ScrollWindowTest : NormalModeIntegrationTest { private static readonly string[] s_lines = KeyInputUtilTest.CharLettersLower.Select(x => x.ToString()).ToArray(); private readonly int _lastLineNumber = 0; protected ScrollWindowTest() { Create(s_lines); _lastLineNumber = _textBuffer.CurrentSnapshot.LineCount - 1; _textView.SetVisibleLineCount(5); _globalSettings.ScrollOffset = 1; _windowSettings.Scroll = 1; } public sealed class WindowAndCaretTest : ScrollWindowTest { [WpfFact] public void UpMovesCaret() { _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(1).Start, 0.0, ViewRelativePosition.Top); _textView.MoveCaretToLine(2); DoEvents(); _vimBuffer.ProcessNotation("<C-u>"); Assert.Equal(1, _textView.GetCaretLine().LineNumber); Assert.Equal(0, _textView.GetFirstVisibleLineNumber()); } /// <summary> /// The caret should move in this case even if the window itself doesn't scroll /// </summary> [WpfFact] public void UpMovesCaretWithoutScroll() { _textView.MoveCaretToLine(2); DoEvents(); _vimBuffer.ProcessNotation("<C-u>"); Assert.Equal(1, _textView.GetCaretLine().LineNumber); } } public sealed class WindowOnlyTest : ScrollWindowTest { public WindowOnlyTest() { _globalSettings.ScrollOffset = 0; } [WpfFact] public void UpDoesNotMoveCaret() { _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(1).Start, 0.0, ViewRelativePosition.Top); _textView.MoveCaretToLine(2); _vimBuffer.ProcessNotation("<C-y>"); Assert.Equal(2, _textView.GetCaretLine().LineNumber); } [WpfFact] public void DownDoesNotMoveCaret() { _textView.MoveCaretToLine(2); _vimBuffer.ProcessNotation("<C-e>"); Assert.Equal(_textView.GetPointInLine(2, 0), _textView.GetCaretPoint()); } /// <summary> /// When the caret moves off the visible screen we move it to be visible /// </summary> [WpfFact] public void DownMovesCaretWhenNotVisible() { _textView.MoveCaretToLine(0); _vimBuffer.ProcessNotation("<C-e>"); Assert.Equal(_textView.GetFirstVisibleLineNumber(), _textView.GetCaretLine().LineNumber); } /// <summary> /// As the lines move off of the screen the caret is moved down to keep it visible. Make sure /// that we maintain the caret column in these cases /// </summary> [WpfFact] public void DownMaintainCaretColumn() { _textBuffer.SetText("cat", "", "dog", "a", "b", "c", "d", "e"); _textView.MoveCaretToLine(0, 1); _vimBuffer.ProcessNotation("<C-e>"); Assert.Equal(_textBuffer.GetPointInLine(1, 0), _textView.GetCaretPoint()); _vimBuffer.ProcessNotation("<C-e>"); Assert.Equal(_textBuffer.GetPointInLine(2, 1), _textView.GetCaretPoint()); } /// <summary> /// When the scroll is to the top of the ITextBuffer the Ctrl-Y command should not cause the /// caret to move. It should only move as the result of the window scrolling the caret out of /// the view /// </summary> [WpfFact] public void Issue1202() { _textView.MoveCaretToLine(1); _vimBuffer.ProcessNotation("<C-y>"); Assert.Equal(1, _textView.GetCaretLine().LineNumber); } [WpfFact] public void Issue1637() { _textBuffer.SetText("abcdefghi".Select(x => x.ToString()).ToArray()); _globalSettings.ScrollOffset = 1; _vimBuffer.ProcessNotation("<C-e>"); Assert.Equal("c", _textView.GetCaretLine().GetText()); Assert.Equal(1, _textView.GetFirstVisibleLineNumber()); } } public sealed class WindowMotionTest : ScrollWindowTest { public WindowMotionTest() { _globalSettings.ScrollOffset = 0; } private void PutLineAtTop(int line) { _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(line).Start, 0.0, ViewRelativePosition.Top); } /// <summary> /// Move to home should position on the first visible line /// </summary> [WpfFact] public void MoveToHome() { var caretLine = 8; _textView.MoveCaretToLine(caretLine); var topLine = 5; PutLineAtTop(topLine); _vimBuffer.ProcessNotation("H"); Assert.Equal(topLine, _textView.GetCaretLine().LineNumber); } /// <summary> /// Move to home should position on the first visible line adjusted for scrolloff /// </summary> [WpfFact] public void MoveToHomeScrollOffset() { var caretLine = 8; _textView.MoveCaretToLine(caretLine); var topLine = 5; _globalSettings.ScrollOffset = 2; PutLineAtTop(topLine); _vimBuffer.ProcessNotation("H"); var expected = topLine + _globalSettings.ScrollOffset; Assert.Equal(expected, _textView.GetCaretLine().LineNumber); } /// <summary> /// Move to home should position on the first visible line adjusted for scrolloff /// </summary> [WpfFact] public void MoveToHomeScrollOffsetAtTop() { _globalSettings.ScrollOffset = 2; var caretLine = 4; _textView.MoveCaretToLine(caretLine); DoEvents(); var topLine = 0; PutLineAtTop(topLine); _vimBuffer.ProcessNotation("H"); Assert.Equal(0, _textView.GetCaretLine().LineNumber); } /// <summary> /// Delete to home should delete from home to the current line /// </summary> [WpfFact] public void DeleteToHome() { // Reported in issue #1093. var lineCount = _textBuffer.CurrentSnapshot.LineCount; var caretLine = 8; _textView.MoveCaretToLine(caretLine); var topLine = 5; PutLineAtTop(topLine); _vimBuffer.ProcessNotation("dH"); var expected = lineCount - (caretLine - topLine + 1); Assert.Equal(expected, _textBuffer.CurrentSnapshot.LineCount); } /// <summary> /// Delete to last should delete from the current line to the last window line /// </summary> [WpfFact] public void DeleteToLast() { var lineCount = _textBuffer.CurrentSnapshot.LineCount; var caretLine = 6; _textView.MoveCaretToLine(caretLine); var topLine = 5; PutLineAtTop(topLine); var bottomLine = _textView.GetLastVisibleLineNumber(); _vimBuffer.ProcessNotation("dL"); var expected = lineCount - (bottomLine - caretLine + 1); Assert.Equal(expected, _textBuffer.CurrentSnapshot.LineCount); } } } public sealed class ScrollWithFinalNewLineTest : NormalModeIntegrationTest { private static readonly string[] s_lines = KeyInputUtilTest.CharLettersLower.Select(x => x.ToString()).ToArray(); private readonly int _lastLineNumber = 0; private readonly int _visibleLines = 10; public ScrollWithFinalNewLineTest() { Create(s_lines.Concat(new[] { "" }).ToArray()); _lastLineNumber = _textBuffer.CurrentSnapshot.LineCount - 2; _textView.SetVisibleLineCount(_visibleLines); } /// <summary> /// When using Ctrl-F on a buffer with a final newline, we can't reach the phantom line /// </summary> [WpfFact] public void ScrollPageCantReachPhantomLine() { var topLine = _lastLineNumber - 1; _textView.MoveCaretToLine(topLine); _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(topLine).Start, 0.0, ViewRelativePosition.Top); _vimBuffer.ProcessNotation("<C-f>"); Assert.Equal(_lastLineNumber, _textView.GetCaretLine().LineNumber); } /// <summary> /// When using Ctrl-D on a buffer with a final newline, we can't reach the phantom line /// </summary> [WpfFact] public void ScrollLinesCantReachPhantomLine() { var topLine = _lastLineNumber - 1; _textView.MoveCaretToLine(topLine); _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(topLine).Start, 0.0, ViewRelativePosition.Top); _vimBuffer.ProcessNotation("<C-d>"); Assert.Equal(_lastLineNumber, _textView.GetCaretLine().LineNumber); } } public sealed class ScrollOffsetTest : NormalModeIntegrationTest { private static readonly string[] s_lines = KeyInputUtilTest.CharLettersLower.Select(x => x.ToString()).ToArray(); private readonly int _lastLineNumber = 0; public ScrollOffsetTest() { Create(s_lines); _lastLineNumber = _textBuffer.CurrentSnapshot.LineCount - 1; _textView.SetVisibleLineCount(5); _globalSettings.ScrollOffset = 2; } private void AssertFirstLine(int lineNumber) { DoEvents(); var actual = _textView.GetFirstVisibleLineNumber(); Assert.Equal(lineNumber, actual); } private void AssertLastLine(int lineNumber) { DoEvents(); var actual = _textView.GetLastVisibleLineNumber(); Assert.Equal(lineNumber, actual); } [WpfFact] public void SimpleMoveDown() { _textView.ScrollToTop(); AssertLastLine(4); _textView.MoveCaretToLine(2); _vimBuffer.ProcessNotation("j"); AssertLastLine(5); } [WpfFact] public void SimpleMoveUp() { var lineNumber = 20; _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(lineNumber).Start, 0.0, ViewRelativePosition.Top); _textView.MoveCaretToLine(lineNumber + 2); AssertFirstLine(lineNumber); _vimBuffer.ProcessNotation("k"); AssertFirstLine(lineNumber - 1); } /// <summary> /// During an incremental search even though the caret doesn't move we should still position /// the scroll as if the caret was at the found search point /// </summary> [WpfFact] public async void IncrementalSearchForward() { _globalSettings.IncrementalSearch = true; _textView.ScrollToTop(); _textView.MoveCaretToLine(0); _vimBuffer.ProcessNotation("/g"); await _vimBuffer.GetSearchCompleteAsync(); AssertLastLine(8); } [WpfFact] public void ScrollDownLines() { _textView.ScrollToTop(); _textView.MoveCaretToLine(2); _windowSettings.Scroll = 2; _vimBuffer.ProcessNotation("<c-d>"); AssertFirstLine(2); Assert.Equal(4, _textView.GetCaretLine().LineNumber); } [WpfFact] public void ScrollUpLines() { var lineNumber = 16; _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(lineNumber).Start, 0.0, ViewRelativePosition.Top); _textView.MoveCaretToLine(lineNumber + 2); _windowSettings.Scroll = 2; AssertFirstLine(lineNumber); _vimBuffer.ProcessNotation("<c-u>"); AssertFirstLine(lineNumber - 2); Assert.Equal(lineNumber, _textView.GetCaretLine().LineNumber); } [WpfFact] public void ScrollLineToTop() { var lineNumber = 4; _textView.SetVisibleLineCount(10); _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(lineNumber).Start, 0.0, ViewRelativePosition.Top); _textView.MoveCaretToLine(lineNumber + 4); _vimBuffer.ProcessNotation("zt"); AssertFirstLine(lineNumber + 2); } /// <summary> /// The simple act of moving the caret outside of the context of a vim command shousd cause the scroll /// offset to be respected /// </summary> [WpfFact] public void CaretMove() { _textView.ScrollToTop(); _textView.MoveCaretToLine(4); DoEvents(); AssertFirstLine(2); } [WpfFact] public void ScrollDownLines_AtBottom() { // Reported in issue #2248. _globalSettings.ScrollOffset = 1; var lineNumber = _textBuffer.CurrentSnapshot.LineCount - 1; _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(lineNumber).Start, 0.0, ViewRelativePosition.Bottom); _textView.MoveCaretToLine(lineNumber); DoEvents(); _vimBuffer.ProcessNotation("<c-d>"); Assert.Equal(lineNumber, _textView.GetCaretLine().LineNumber); } [WpfFact] public void ScrollUpLines_AtTop() { // Reported in issue #2248. _globalSettings.ScrollOffset = 1; var lineNumber = 0; _textView.DisplayTextLineContainingBufferPosition(_textBuffer.GetLine(lineNumber).Start, 0.0, ViewRelativePosition.Top); _textView.MoveCaretToLine(lineNumber); _vimBuffer.ProcessNotation("<c-u>"); Assert.Equal(lineNumber, _textView.GetCaretLine().LineNumber); } } public sealed class SmallDeleteTest : NormalModeIntegrationTest { [WpfFact] public void DeleteThenPaste() { Create("dog cat"); _vimBuffer.ProcessNotation(@"x""-p"); Assert.Equal("odg cat", _textBuffer.GetLine(0).GetText()); } /// <summary> /// Deleting a line shouldn't effect the small delete register /// </summary> [WpfFact] public void DeleteLine() { Create("dog", "cat", "tree"); _textView.MoveCaretToLine(2); _vimBuffer.Process("x"); Assert.Equal("t", RegisterMap.GetRegister(RegisterName.SmallDelete).StringValue); _textView.MoveCaretToLine(0); _vimBuffer.Process(@"dd""-p"); Assert.Equal("ctat", _textBuffer.GetLine(0).GetText()); } /// <summary> /// As long as the delete is less than one line then the delete should /// update the small delete register /// </summary> [WpfFact] public void DeleteMoreThanOneCharacter() { Create("dog", "cat"); _vimBuffer.ProcessNotation(@"2x""-p"); Assert.Equal("gdo", _textBuffer.GetLine(0).GetText()); } /// <summary> /// Deleting multiple lines but not ending on a new line should still not update the /// small delete register /// </summary> [WpfFact] public void DeleteLineDoesntEndInNewLine() { Create("dog", "cat", "tree"); _textView.MoveCaretToLine(2); _vimBuffer.Process("x"); Assert.Equal("t", RegisterMap.GetRegister(RegisterName.SmallDelete).StringValue); _textView.MoveCaretToLine(0); _vimBuffer.Process(@"vjx""-p"); Assert.Equal("att", _textBuffer.GetLine(0).GetText()); } /// <summary> /// When the delete occurs into a named register then we should not update the small /// delete register /// </summary> [WpfFact] public void IgnoreNamedRegister() { Create("dog"); RegisterMap.GetRegister(RegisterName.SmallDelete).UpdateValue("t"); _vimBuffer.Process(@"""cx""-p"); Assert.Equal("otg", _textBuffer.GetLine(0).GetText()); } /// <summary> /// The search motion should always cause the 1-9 registers to be updated irrespective of the text of the /// delete. /// </summary> [WpfFact] public void DeleteSmallWithSearchMotion() { Create("dog"); RegisterMap.GetRegister(1).UpdateValue("g"); _vimBuffer.Process(@"d/o", enter: true); Assert.Equal("d", RegisterMap.GetRegister(1).StringValue); Assert.Equal("g", RegisterMap.GetRegister(2).StringValue); Assert.Equal("d", RegisterMap.GetRegister(RegisterName.SmallDelete).StringValue); } [WpfFact] public void ChangeSmallWithSearchMotion() { Create("dog"); RegisterMap.GetRegister(1).UpdateValue("g"); _vimBuffer.Process(@"c/o", enter: true); Assert.Equal("d", RegisterMap.GetRegister(1).StringValue); Assert.Equal("g", RegisterMap.GetRegister(2).StringValue); Assert.Equal("d", RegisterMap.GetRegister(RegisterName.SmallDelete).StringValue); } [WpfFact] public void Issue1436() { Create("cat", "dog", "fish", "tree"); var span = new SnapshotSpan( _textBuffer.GetLine(1).Start.Add(2), _textBuffer.GetLine(2).End); var adhocOutliner = TaggerUtil.GetOrCreateOutliner(_textBuffer); adhocOutliner.CreateOutliningRegion(span, SpanTrackingMode.EdgeInclusive, "test", "test"); OutliningManagerService.GetOutliningManager(_textView).CollapseAll(span, _ => true); _textView.MoveCaretTo(_textBuffer.GetLine(2).End); _vimBuffer.ProcessNotation("dd"); Assert.Equal(new[] { "cat", "tree" }, _textBuffer.GetLines()); } /// <summary> /// Deleting a character before the caret should handle an external edit /// </summary> [WpfFact] public void DeleteCharBeforeCaret_ExternalEdit() { Create("cat", "dog", "fish", ""); _textBuffer.Changed += (sender, obj) => { if (_textBuffer.GetSpan(0, 1).GetText() == "c") { _textBuffer.Delete(new Span(0, 1)); } }; _textView.MoveCaretToLine(1, 1); _vimBuffer.ProcessNotation("X"); diff --git a/Test/VimCoreTest/VisualModeIntegrationTest.cs b/Test/VimCoreTest/VisualModeIntegrationTest.cs index bc81f8c..1ba98b2 100644 --- a/Test/VimCoreTest/VisualModeIntegrationTest.cs +++ b/Test/VimCoreTest/VisualModeIntegrationTest.cs @@ -1649,1024 +1649,1037 @@ namespace Vim.UnitTest public void EndOfLine() { Create("dog", "x", "tree"); _vimBuffer.ProcessNotation(@"l<C-q>jjI#<Esc>"); Assert.Equal(new[] { "d#og", "x#", "t#ree" }, _textBuffer.GetLines()); } /// <summary> /// On completely empty lines a block insertion should apply to /// all lines /// </summary> [WpfFact] public void AllEmptyLines() { // Reported in issue #2675. Create("", "", "", ""); _vimBuffer.ProcessNotation(@"<C-q>jjI#<Esc>"); Assert.Equal(new[] { "#", "#", "#", ""}, _textBuffer.GetLines()); } } public sealed class SurrogatePairTest: BlockInsertTest { /// <summary> /// Block insert should not be splitting surrogate pairs into spaces as it does for non-surrogate /// pairs which comprise multiple spaces. /// </summary> [WpfFact] public void MiddleOfSurrogatePair() { const string alien = "\U0001F47D"; // 👽 Create( "dogs", $"{alien}{alien}{alien}", "trees"); _vimBuffer.ProcessNotation(@"l<C-q>jjI#<Esc>"); Assert.Equal( new[] { "d#ogs", $"#{alien}{alien}{alien}", "t#rees" }, _textBuffer.GetLines()); } [WpfFact] public void MiddleOfSurrogatePairNonFirstColumn() { const string alien = "\U0001F47D"; // 👽 Create( "dogs", $"{alien}{alien}{alien}", "trees"); _vimBuffer.ProcessNotation(@"lll<C-q>jjI#<Esc>"); Assert.Equal( new[] { "dog#s", $"{alien}#{alien}{alien}", "tre#es" }, _textBuffer.GetLines()); } [WpfFact] public void Normal() { const string alien = "\U0001F47D"; // 👽 Create( "doggies", $"{alien}{alien}{alien}", "trees"); _vimBuffer.ProcessNotation(@"ll<C-q>jjI#<Esc>"); Assert.Equal( new[] { "do#ggies", $"{alien}#{alien}{alien}", "tr#ees" }, _textBuffer.GetLines()); } [WpfFact] public void EndOfLine() { const string alien = "\U0001F47D"; // 👽 Create( "dos", $"{alien}", "bi"); _vimBuffer.ProcessNotation(@"ll<C-q>jjIg<Esc>"); Assert.Equal( new[] { "dogs", $"{alien}g", "big", }, _textBuffer.GetLines()); } [WpfFact] public void StartingOnSurrogatePair() { const string alien = "\U0001F47D"; // 👽 Create( $"{alien}{alien}{alien}", "dogs", "trees"); _vimBuffer.ProcessNotation(@"l<C-q>jjI#<Esc>"); Assert.Equal( new[] { $"{alien}#{alien}{alien}", "do#gs", "tr#ees", }, _textBuffer.GetLines()); } } public sealed class InsertTabTest : BlockInsertTest { /// <summary> /// A block inserted tab with 'expandtab' should obey the starting column /// </summary> [WpfFact] public void UnalignedExpandTabs() { // Reported in issue #2073. Create(" dog", " cat", " bat", ""); _vimBufferData.LocalSettings.TabStop = 4; _vimBufferData.LocalSettings.ExpandTab = true; EnterBlock(_textView.GetBlockSpan(1, 1, 0, 3)); _vimBuffer.ProcessNotation("<S-i><Tab><Esc>"); Assert.Equal(new[] { " dog", " cat", " bat", "", }, _textBuffer.GetLines()); } /// <summary> /// A block inserted tab with 'noexpandtab' should eat preceding spaces if possible /// </summary> [WpfFact] public void UnalignedNoExpandTabs() { Create(" dog", " cat", " bat", ""); _vimBufferData.LocalSettings.TabStop = 4; _vimBufferData.LocalSettings.ExpandTab = false; EnterBlock(_textView.GetBlockSpan(1, 1, 0, 3)); _vimBuffer.ProcessNotation("<S-i><Tab><Esc>"); Assert.Equal(new[] { "\tdog", "\tcat", "\tbat", "", }, _textBuffer.GetLines()); } /// <summary> /// A block inserted tab with 'noexpandtab' should not eat preceding non-spaces /// </summary> [WpfFact] public void UnalignedNoExpandTabsNotSpaces() { Create("xdog", "xcat", "xbat", ""); _vimBufferData.LocalSettings.TabStop = 4; _vimBufferData.LocalSettings.ExpandTab = false; EnterBlock(_textView.GetBlockSpan(1, 1, 0, 3)); _vimBuffer.ProcessNotation("<S-i><Tab><Esc>"); Assert.Equal(new[] { "x\tdog", "x\tcat", "x\tbat", "", }, _textBuffer.GetLines()); } /// <summary> /// A block inserted tab should allow custom processing on each /// line, and in Visual Studio a tab expands to the shiftwidth /// </summary> [WpfFact] public void CustomProcessedTab() { // Reported in issue #2420. Create("dog", "cat", "bat", ""); _vimBufferData.LocalSettings.TabStop = 8; _vimBufferData.LocalSettings.ShiftWidth = 4; _vimBufferData.LocalSettings.ExpandTab = true; EnterBlock(_textView.GetBlockSpan(0, 1, 0, 3)); _vimHost.TryCustomProcessFunc = (textView, insertCommand) => { if (insertCommand.IsInsertTab) { _textBuffer.Insert(_textView.GetCaretPoint().Position, " "); return true; } return false; }; _vimBuffer.ProcessNotation("<S-i><Tab><Esc>"); Assert.Equal(new[] { " dog", " cat", " bat", "", }, _textBuffer.GetLines()); } /// <summary> /// Without custom processing, a tab in vim expands to the /// tabstop, not shiftwidth /// </summary> [WpfFact] public void NonCustomProcessedTab() { // Reported in issue #2420. Create("dog", "cat", "bat", ""); _vimBufferData.LocalSettings.TabStop = 8; _vimBufferData.LocalSettings.ShiftWidth = 4; _vimBufferData.LocalSettings.ExpandTab = true; EnterBlock(_textView.GetBlockSpan(0, 1, 0, 3)); _vimBuffer.ProcessNotation("<S-i><Tab><Esc>"); Assert.Equal(new[] { " dog", " cat", " bat", "", }, _textBuffer.GetLines()); } } public sealed class AppendEndTest : BlockInsertTest { /// <summary> /// Using shift-a from visual block mode appends starting at /// the column of the end of the primary block span /// </summary> [WpfFact] public void Basic() { // Reported in issue #2667. Create("hot dog", "fat cat", "big bat", ""); EnterBlock(_textView.GetBlockSpan(0, 4, 0, 3)); _vimBuffer.ProcessNotation("<S-a>x <Esc>"); Assert.Equal(new[] { "hot x dog", "fat x cat", "big x bat", "" }, _textBuffer.GetLines()); } /// <summary> /// Using shift-a from visual block mode differs from shift-i /// with respect to short lines, specifically it pads them /// </summary> [WpfFact] public void ShortLine() { Create("hot dog", "", "big bat", ""); EnterBlock(_textView.GetBlockSpan(0, 4, 0, 3)); _vimBuffer.ProcessNotation("<S-a>x <Esc>"); Assert.Equal(new[] { "hot x dog", " x ", "big x bat", "" }, _textBuffer.GetLines()); } } public sealed class AppendEndOfLineTabTest : BlockInsertTest { /// <summary> /// A block appended tab with 'expandtab' should obey the starting column /// </summary> [WpfFact] public void UnalignedExpandTabs() { Create(" dog ", " cat ", " bat ", ""); _vimBufferData.LocalSettings.TabStop = 4; _vimBufferData.LocalSettings.ExpandTab = true; EnterBlock(_textView.GetBlockSpan(1, 1, 0, 3)); _vimBuffer.ProcessNotation("$<S-a><Tab>x<Esc>"); Assert.Equal(new[] { " dog x", " cat x", " bat x", "", }, _textBuffer.GetLines()); } /// <summary> /// A block appended tab with 'noexpandtab' should eat preceding spaces if possible /// </summary> [WpfFact] public void UnalignedNoExpandTabs() { Create(" dog ", " cat ", " bat ", ""); _vimBufferData.LocalSettings.TabStop = 4; _vimBufferData.LocalSettings.ExpandTab = false; EnterBlock(_textView.GetBlockSpan(1, 1, 0, 3)); _vimBuffer.ProcessNotation("$<S-a><Tab>x<Esc>"); Assert.Equal(new[] { " dog\tx", " cat\tx", " bat\tx", "", }, _textBuffer.GetLines()); } /// <summary> /// A block appended tab with 'noexpandtab' should not eat preceding non-spaces /// </summary> [WpfFact] public void UnalignedNoExpandTabsNotSpaces() { // Reported in issue #2217. Create(" dog_", " cat__", " bat___", ""); _vimBufferData.LocalSettings.TabStop = 4; _vimBufferData.LocalSettings.ExpandTab = false; EnterBlock(_textView.GetBlockSpan(1, 1, 0, 3)); _vimBuffer.ProcessNotation("$<S-a><Tab>x<Esc>"); Assert.Equal(new[] { " dog_\tx", " cat__\tx", " bat___\tx", "", }, _textBuffer.GetLines()); } } public sealed class RepeatTest : BlockInsertTest { /// <summary> /// The repeat of a block insert should work against the same number of lines as the /// original change /// </summary> [WpfFact] public void SameNumberOfLines() { Create("cat", "dog", "fish"); _vimBuffer.ProcessNotation("<C-q>j<S-i>x<Esc>j."); Assert.Equal(new[] { "xcat", "xxdog", "xfish" }, _textBuffer.GetLines()); } /// <summary> /// If the repeat goes off the end of the ITextBuffer then the change should just be /// applied to the lines from the caret to the end /// </summary> [WpfFact] public void PasteEndOfBuffer() { Create("cat", "dog", "fish"); _vimBuffer.ProcessNotation("<C-q>j<S-i>x<Esc>jj."); Assert.Equal(new[] { "xcat", "xdog", "xfish" }, _textBuffer.GetLines()); } /// <summary> /// Spaces don't matter in the repeat. The code should just treat them as normal characters and /// repeat the edits into them /// </summary> [WpfFact] public void DontConsiderSpaces() { Create("cat", "dog", " fish"); _vimBuffer.ProcessNotation("<C-q>j<S-i>x<Esc>jj."); Assert.Equal(new[] { "xcat", "xdog", "x fish" }, _textBuffer.GetLines()); } /// <summary> /// Make sure that we handle deletes properly. So long as it leaves us with a new bit of text then /// we can repeat it /// </summary> [WpfFact] public void HandleDeletes() { Create("cat", "dog", "fish", "store"); _vimBuffer.ProcessNotation("<C-q>j<S-i>xy<BS><Esc>jj."); Assert.Equal(new[] { "xcat", "xdog", "xfish", "xstore" }, _textBuffer.GetLines()); } /// <summary> /// Make sure the code properly handles the case where the insert results in 0 text being added /// to the file. This should cause us to not do anything even on repeat /// </summary> [WpfFact] public void HandleEmptyInsertString() { Create("cat", "dog", "fish", "store"); _vimBuffer.ProcessNotation("<C-q>j<S-i>xy<BS><BS><Esc>jj."); Assert.Equal(new[] { "cat", "dog", "fish", "store" }, _textBuffer.GetLines()); } [WpfFact] public void Issue1136() { Create("cat", "dog"); _vimBuffer.ProcessNotation("<C-q>j<S-i>x<Esc>."); Assert.Equal(new[] { "xxcat", "xxdog" }, _textBuffer.GetLines()); } } } public sealed class BlockChange : VisualModeIntegrationTest { /// <summary> /// The block insert should add the text to every column /// </summary> [WpfFact] public void Simple() { Create("dog", "cat", "fish"); _vimBuffer.ProcessNotation("<C-q>jcthe <Esc>"); Assert.Equal("the og", _textBuffer.GetLine(0).GetText()); Assert.Equal("the at", _textBuffer.GetLine(1).GetText()); } /// <summary> /// Make sure an undo of a block edit goes back to the original text and replaces /// the cursor at the start of the block /// </summary> [WpfFact] public void Undo() { Create("dog", "cat", "fish"); _vimBuffer.ProcessNotation("<C-q>jcthe <Esc>u"); Assert.Equal( new[] { "dog", "cat", "fish" }, _textBuffer.GetLines()); Assert.Equal(0, _textView.GetCaretPoint().Position); } [WpfFact] public void RenameFunction() { Create("foo()", "foo()"); _vimBuffer.ProcessNotation("<C-q>jllcbar<Esc>"); Assert.Equal( new[] { "bar()", "bar()" }, _textBuffer.GetLines()); } } public sealed class BlockAdd : VisualModeIntegrationTest { /// <summary> /// The block add should only add to numbers within the selection /// </summary> [WpfTheory] [MemberData(nameof(SelectionOptions))] public void Simple(string selection) { // Reported in issue #2501. Create( " 1 This is the first thing. Here's a number: 99.", "", " 2 This is the second thing.", " Here is another number 123.", "", " 3 This is the last thing.", "" ); _globalSettings.Selection = selection; _vimBuffer.ProcessNotation("<C-q>5j2l<C-a>"); var expected = new[] { " 2 This is the first thing. Here's a number: 99.", "", " 3 This is the second thing.", " Here is another number 123.", "", " 4 This is the last thing.", "" }; Assert.Equal(expected, _textBuffer.GetLines()); } } public sealed class Move : VisualModeIntegrationTest { [WpfFact] public void HomeToStartOfLine() { Create("cat dog"); _textView.MoveCaretTo(2); _vimBuffer.ProcessNotation("v<Home>"); Assert.Equal("cat", _textView.GetSelectionSpan().GetText()); Assert.Equal(0, _textView.GetCaretPoint()); } [WpfFact] public void HomeToStartOfLineViaKeypad() { Create("cat dog"); _textView.MoveCaretTo(2); _vimBuffer.ProcessNotation("v<kHome>"); Assert.Equal("cat", _textView.GetSelectionSpan().GetText()); Assert.Equal(0, _textView.GetCaretPoint()); } /// <summary> /// Jump to a mark and make sure that the selection correctly updates /// </summary> [WpfFact] public void JumpMarkLine_Character() { Create("cat", "dog"); _textView.MoveCaretTo(1); _vimBuffer.MarkMap.SetLocalMark('b', _vimBufferData, 1, 1); _vimBuffer.Process("v'b"); Assert.Equal("at\r\nd", _textView.GetSelectionSpan().GetText()); } /// <summary> /// Jump to a mark and make sure that the selection correctly updates /// </summary> [WpfFact] public void JumpMark_Character() { Create("cat", "dog"); _textView.MoveCaretTo(1); _vimBuffer.MarkMap.SetLocalMark('b', _vimBufferData, 1, 1); _vimBuffer.Process("v`b"); Assert.Equal("at\r\ndo", _textView.GetSelectionSpan().GetText()); } } public abstract class ReplaceSelectionTest : VisualModeIntegrationTest { public sealed class CharacterWiseTest : ReplaceSelectionTest { [WpfFact] public void Simple() { Create("cat dog", "tree fish"); _vimBuffer.ProcessNotation("vllra"); Assert.Equal(new[] { "aaa dog", "tree fish" }, _textBuffer.GetLines()); } [WpfFact] public void ExtendIntoNewLine() { Create("cat", "dog"); _vimBuffer.GlobalSettings.VirtualEdit = "onemore"; _vimBuffer.ProcessNotation("vlllllra"); Assert.Equal(new[] { "aaa", "dog" }, _textBuffer.GetLines()); } [WpfFact] public void MultiLine() { Create("cat", "dog"); _vimBuffer.ProcessNotation("vjra"); Assert.Equal(new[] { "aaa", "aog" }, _textBuffer.GetLines()); } + + [WpfFact] + public void NonAscii() + { + // Reported in issue #2702. + Create("abc", ""); + _vimBuffer.Process("v"); + Assert.False(_vimBuffer.CanProcess(KeyInputUtil.CharToKeyInput('©'))); + _vimBuffer.Process("r"); + Assert.True(_vimBuffer.CanProcess(KeyInputUtil.CharToKeyInput('©'))); + _vimBuffer.Process("©"); + Assert.Equal(new[] { "©bc", "" }, _textBuffer.GetLines()); + } } public sealed class LineWiseTest : ReplaceSelectionTest { [WpfFact] public void Single() { Create("cat", "dog"); _vimBuffer.ProcessNotation("Vra"); Assert.Equal(new[] { "aaa", "dog" }, _textBuffer.GetLines()); } [WpfFact] public void Issue1201() { Create("one two three", "four five six"); _vimBuffer.ProcessNotation("Vr-"); Assert.Equal("-------------", _textBuffer.GetLine(0).GetText()); } } public sealed class BlockWiseTest : ReplaceSelectionTest { /// <summary> /// This is an anti test. /// /// The WPF editor has no way to position the caret in the middle of a /// tab. It can't for instance place it on the 2 space of the 4 spaces /// the caret occupies. Hence this test have a deviating behavior from /// gVim because the caret position differs on the final 'l' /// </summary> [WpfFact] public void Overlap() { Create("cat", "d\tog"); _vimBuffer.LocalSettings.TabStop = 4; _vimBuffer.ProcessNotation("ll<C-q>jlra"); Assert.Equal(new[] { "caa", "d aaag" }, _textBuffer.GetLines()); } } } public sealed class Insert : VisualModeIntegrationTest { /// <summary> /// When switching to insert mode the caret should move to the start of the line /// </summary> [WpfFact] public void MiddleOfLine() { Create("cat", "dog"); _vimBuffer.Process("vllI"); Assert.Equal(0, _textView.GetCaretPoint().Position); Assert.Equal(ModeKind.Insert, _vimBuffer.ModeKind); } } public sealed class ParagraphTest : VisualModeIntegrationTest { /// <summary> /// Inner paragraph is always linewise /// </summary> [WpfFact] public void InnerLinewise() { // Reported in issue #2006. Create("ram", "goat", "", "cat", "dog", "", "bat", "bear"); _textView.MoveCaretToLine(3); _vimBuffer.Process("vip"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); _vimBuffer.Process("y"); Assert.True(UnnamedRegister.OperationKind.IsLineWise); } /// <summary> /// Outer paragraph is always linewise /// </summary> [WpfFact] public void OuterLinewise() { Create("ram", "goat", "", "cat", "dog", "", "bat", "bear"); _textView.MoveCaretToLine(3); _vimBuffer.Process("vip"); Assert.Equal(ModeKind.VisualLine, _vimBuffer.ModeKind); _vimBuffer.Process("y"); Assert.True(UnnamedRegister.OperationKind.IsLineWise); } } public sealed class SelectionTest : VisualModeIntegrationTest { /// <summary> /// In Visual Mode it is possible to move the caret past the end of the line even if /// 'virtualedit='. /// </summary> [WpfFact] public void MoveToEndOfLineCharacter() { Create("cat", "dog"); _vimBuffer.Process("vlll"); Assert.Equal(3, _textView.GetCaretPoint().Position); } [WpfFact] public void MoveToEndOfLineLine() { Create("cat", "dog"); _vimBuffer.Process("Vlll"); Assert.Equal(3, _textView.GetCaretPoint().Position); } [WpfFact] public void Issue1790() { Create(" the"); _vimBuffer.Process("vas"); Assert.Equal(_textBuffer.GetSpan(start: 0, length: 4), _textView.GetSelectionSpan()); } } public abstract class TagBlockTest : VisualModeIntegrationTest { public sealed class CharacterWiseTest : TagBlockTest { [WpfFact] public void InnerSimpleMultiLine() { Create("<a>", "blah", "</a>"); _textView.MoveCaretToLine(1); _vimBuffer.Process("vity"); Assert.Equal(Environment.NewLine + "blah" + Environment.NewLine, UnnamedRegister.StringValue); } /// <summary> /// Visual selection of a block from an empty line should not expand /// </summary> [WpfFact] public void InnerSimpleMultiLineFromEmptyLine() { // Reported in issue #2081. Create("<a>", "", "blah", "</a>"); _textView.MoveCaretToLine(1); _vimBuffer.Process("vity"); Assert.Equal(Environment.NewLine + Environment.NewLine + "blah" + Environment.NewLine, UnnamedRegister.StringValue); } [WpfFact] public void InnerSimpleSingleLine() { Create("<a>blah</a>"); _textView.MoveCaretTo(4); _vimBuffer.Process("vit"); var span = new Span(_textBuffer.GetPointInLine(0, 3), 4); Assert.Equal(span, _textView.GetSelectionSpan()); } [WpfFact] public void AllSimpleSingleLine() { Create("<a>blah</a>"); _textView.MoveCaretTo(4); _vimBuffer.Process("vat"); var span = new Span(_textBuffer.GetPoint(0), _textBuffer.CurrentSnapshot.Length); Assert.Equal(span, _textView.GetSelectionSpan()); } [WpfTheory] [InlineData("inclusive")] [InlineData("exclusive")] public void SelectPartialInnerExpandAll(string selectionSetting) { Create("<a><b><c/></b></a>"); _globalSettings.Selection = selectionSetting; _textView.MoveCaretTo("<a><b><c".Length); _vimBuffer.Process("vlit"); Assert.Equal("<c/>", _textView.GetSelectionSpan().GetText()); } [WpfFact] public void SelectFullInnerExpandAll() { Create("<parent>", "<child>", "<grandchild />", "</child>", "</parent>"); var initialPosition = _textBuffer.GetLineFromLineNumber(2).Start; _textView.MoveCaretTo(initialPosition); _vimBuffer.Process("vitat"); Assert.Equal(_textBuffer.GetLineRange(1, 3).Extent, _textView.GetSelectionSpan()); } [WpfFact] public void SelectMultiLineTag() { Create("<parent>", "<child", "attr1=\"value1\"", "attr2", "=", "\"value2\"", ">", "content", "</child>", "</parent>"); var initialPosition = _textBuffer.GetLineFromLineNumber(7).Start; _textView.MoveCaretTo(initialPosition); _vimBuffer.Process("vat"); Assert.Equal(_textBuffer.GetLineRange(1, 8).Extent, _textView.GetSelectionSpan()); } [WpfTheory] [InlineData("inclusive", 1)] [InlineData("exclusive", 0)] public void EmptyTag_SelectInnerExpandInner(string selectionSetting, int selectionLength) { Create("<parent>", "<child>", "<grandchild></grandchild>", "</child>", "</parent>"); _globalSettings.Selection = selectionSetting; var initialPosition = _textBuffer.GetLineSpan(2, "<grandchild>".Length - 1, 0).Start; _textView.MoveCaretTo(initialPosition); _vimBuffer.Process("vit"); Assert.Equal(_textBuffer.GetLineSpan(2, "<grandchild>".Length, selectionLength), _textView.GetSelectionSpan()); _vimBuffer.Process("it"); Assert.Equal(_textBuffer.GetLine(2).Extent, _textView.GetSelectionSpan()); } } public sealed class ExpandSelectionTest : TagBlockTest { [WpfFact] public void InnerSimple() { var text = "<a>blah</a>"; Create(text); _textView.MoveCaretTo(5); _vimBuffer.Process("vit"); Assert.Equal("blah", _textView.GetSelectionSpan().GetText()); _vimBuffer.Process("it"); Assert.Equal(text, _textView.GetSelectionSpan().GetText()); } [WpfFact] public void InnerNestedNoPadding() { var text = "<a><b>blah</b></a>"; Create(text); _textView.MoveCaretTo(7); _vimBuffer.Process("vit"); Assert.Equal("blah", _textView.GetSelectionSpan().GetText()); _vimBuffer.Process("it"); Assert.Equal("<b>blah</b>", _textView.GetSelectionSpan().GetText()); _vimBuffer.Process("it"); Assert.Equal(text, _textView.GetSelectionSpan().GetText()); } [WpfFact] public void InnerNestedPadding() { var text = "<a> <b>blah</b></a>"; Create(text); _textView.MoveCaretTo(7); _vimBuffer.Process("vit"); Assert.Equal("blah", _textView.GetSelectionSpan().GetText()); _vimBuffer.Process("it"); Assert.Equal("<b>blah</b>", _textView.GetSelectionSpan().GetText()); _vimBuffer.Process("it"); Assert.Equal(" <b>blah</b>", _textView.GetSelectionSpan().GetText()); _vimBuffer.Process("it"); Assert.Equal(text, _textView.GetSelectionSpan().GetText()); } [WpfFact] public void AllNested() { var text = "<a><b>blah</b></a>"; Create(text); _textView.MoveCaretTo(7); _vimBuffer.Process("vat"); Assert.Equal("<b>blah</b>", _textView.GetSelectionSpan().GetText()); _vimBuffer.Process("at"); Assert.Equal(text, _textView.GetSelectionSpan().GetText()); } } } public abstract class InvertSelectionTest : VisualModeIntegrationTest { public sealed class CharacterWiseTest : InvertSelectionTest { [WpfFact] public void Simple() { Create("cat and the dog"); _vimBuffer.Process("vlllo"); Assert.Equal(0, _textView.GetCaretPoint().Position); Assert.Equal(4, _textView.Selection.AnchorPoint.Position); Assert.Equal("cat ", _textView.GetSelectionSpan().GetText()); } [WpfFact] public void SingleCharacterSelected() { Create("cat"); _vimBuffer.Process("voooo"); Assert.Equal(0, _textView.GetCaretPoint().Position); Assert.Equal(0, _textView.Selection.AnchorPoint.Position); Assert.Equal("c", _textView.GetSelectionSpan().GetText()); } [WpfFact] public void BackAndForth() { Create("cat and the dog"); _vimBuffer.Process("vllloo"); Assert.Equal(3, _textView.GetCaretPoint().Position); Assert.Equal(0, _textView.Selection.AnchorPoint.Position); Assert.Equal("cat ", _textView.GetSelectionSpan().GetText()); } [WpfFact] public void Multiline() { Create("cat", "dog"); _vimBuffer.Process("lvjo"); var span = _textView.GetSelectionSpan(); Assert.Equal("at" + Environment.NewLine + "do", span.GetText()); Assert.True(_textView.Selection.IsReversed); Assert.Equal(1, _textView.GetCaretPoint().Position); } [WpfFact] public void PastEndOfLine() { Create("cat", "dog"); _vimBuffer.GlobalSettings.VirtualEdit = "onemore"; _vimBuffer.Process("vlllo"); Assert.Equal(4, _textView.Selection.StreamSelectionSpan.Length); Assert.Equal(0, _textView.GetCaretPoint().Position); } [WpfFact] public void PastEndOfLineReverse() { Create("cat", "dog"); _vimBuffer.GlobalSettings.VirtualEdit = "onemore"; _vimBuffer.Process("vllloo"); Assert.Equal(4, _textView.Selection.StreamSelectionSpan.Length); Assert.Equal(3, _textView.GetCaretPoint().Position); } } public sealed class LineWiseTest : InvertSelectionTest { [WpfFact] public void Simple() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("Vjo"); Assert.Equal(0, _textView.GetCaretPoint()); var span = _textView.GetSelectionSpan(); Assert.Equal("cat" + Environment.NewLine + "dog" + Environment.NewLine, span.GetText()); } [WpfFact] public void BackAndForth() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("Vjoo"); Assert.Equal(_textBuffer.GetLine(1).Start, _textView.GetCaretPoint()); var span = _textView.GetSelectionSpan(); Assert.Equal("cat" + Environment.NewLine + "dog" + Environment.NewLine, span.GetText()); } [WpfFact] public void SimpleNonZeroStart() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("lVjo"); Assert.Equal(1, _textView.GetCaretPoint()); var span = _textView.GetSelectionSpan(); Assert.Equal("cat" + Environment.NewLine + "dog" + Environment.NewLine, span.GetText()); } [WpfFact] public void StartOnEmptyLine() { Create("cat", "", "dog", "tree"); _textView.MoveCaretTo(_textBuffer.GetLine(1).Start); _vimBuffer.ProcessNotation("Vjo"); Assert.Equal(_textBuffer.GetLine(1).Start, _textView.GetCaretPoint()); var span = _textView.GetSelectionSpan(); Assert.Equal(Environment.NewLine + "dog" + Environment.NewLine, span.GetText()); } } public sealed class BlockTest : InvertSelectionTest { [WpfFact] public void Simple() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("<C-q>ljo"); Assert.Equal(0, _textView.GetCaretPoint().Position); var blockSpan = _vimBuffer.GetSelectionBlockSpan(); Assert.Equal(2, blockSpan.Height); Assert.Equal(2, blockSpan.SpacesLength); } [WpfFact] public void SimpleBackAndForth() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("<C-q>ljoo"); Assert.Equal(_textView.GetPointInLine(1, 1), _textView.GetCaretPoint().Position); var blockSpan = _vimBuffer.GetSelectionBlockSpan(); Assert.Equal(2, blockSpan.Height); Assert.Equal(2, blockSpan.SpacesLength); } } public sealed class BlockColumnOnlyTest : InvertSelectionTest { [WpfFact] public void Simple() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("<C-q>ljO"); Assert.Equal(_textView.GetPointInLine(1, 0), _textView.GetCaretPoint().Position); var blockSpan = _vimBuffer.GetSelectionBlockSpan(); Assert.Equal(2, blockSpan.Height); Assert.Equal(2, blockSpan.SpacesLength); } [WpfFact] public void SimpleBackAndForth() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("<C-q>ljOO"); Assert.Equal(_textView.GetPointInLine(1, 1), _textView.GetCaretPoint().Position); var blockSpan = _vimBuffer.GetSelectionBlockSpan(); Assert.Equal(2, blockSpan.Height); Assert.Equal(2, blockSpan.SpacesLength); } [WpfFact] public void SimpleReverse() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("<C-q>ljoO"); Assert.Equal(_textView.GetPointInLine(0, 1), _textView.GetCaretPoint().Position); var blockSpan = _vimBuffer.GetSelectionBlockSpan(); Assert.Equal(2, blockSpan.Height); Assert.Equal(2, blockSpan.SpacesLength); } [WpfFact] public void SimpleReverseAndForth() { Create("cat", "dog", "tree"); _vimBuffer.ProcessNotation("<C-q>ljoOO"); Assert.Equal(_textView.GetPointInLine(0, 0), _textView.GetCaretPoint().Position); var blockSpan = _vimBuffer.GetSelectionBlockSpan(); Assert.Equal(2, blockSpan.Height); Assert.Equal(2, blockSpan.SpacesLength); } } } public sealed class KeyMappingTest : VisualModeIntegrationTest { [WpfFact] public void VisualAfterCount() { Create("cat dog"); _vimBuffer.Process(":vmap <space> l", enter: true); _vimBuffer.ProcessNotation("v2<Space>"); Assert.Equal(2, _textView.GetCaretPoint().Position); Assert.Equal("cat", _textView.GetSelectionSpan().GetText()); } [WpfFact] public void Issue890() { Create("cat > dog"); _vimBuffer.ProcessNotation(@":vmap > >gv", enter: true); _vimBuffer.ProcessNotation(@"vf>"); Assert.Equal(ModeKind.VisualCharacter, _vimBuffer.ModeKind); Assert.Equal(4, _textView.GetCaretPoint().Position); } } public sealed class CanProcessTest : VisualModeIntegrationTest { [WpfFact] public void Simple() { Create(""); Assert.True(_vimBuffer.CanProcess('l')); Assert.True(_vimBuffer.CanProcess('k')); } } public sealed class ChangeCase : VisualModeIntegrationTest { [WpfFact] public void Upper_Character() { Create("cat dog"); _vimBuffer.ProcessNotation("vllU"); Assert.Equal("CAT dog", _textBuffer.GetLine(0).GetText()); Assert.Equal(0, _textView.GetCaretColumn().ColumnNumber); } [WpfFact] public void Lower_Character() { Create("CAT dog"); _vimBuffer.ProcessNotation("vllu"); diff --git a/Test/VsVimSharedTest/VsCommandTargetTest.cs b/Test/VsVimSharedTest/VsCommandTargetTest.cs index 015dd00..8e5d296 100644 --- a/Test/VsVimSharedTest/VsCommandTargetTest.cs +++ b/Test/VsVimSharedTest/VsCommandTargetTest.cs @@ -1,720 +1,720 @@ using System; using System.Windows.Input; using Vim.EditorHost; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Moq; using Xunit; using Vim; using Vim.Extensions; using Vim.UnitTest; using Vim.VisualStudio.Implementation; using Vim.VisualStudio.Implementation.Misc; using Microsoft.VisualStudio.Text; using System.Collections.Generic; using Vim.VisualStudio.Implementation.ReSharper; namespace Vim.VisualStudio.UnitTest { public abstract class VsCommandTargetTest : VimTestBase { private readonly MockRepository _factory; private readonly IVimBuffer _vimBuffer; private readonly IVim _vim; private readonly ITextBuffer _textBuffer; private readonly ITextView _textView; private readonly Mock<IVsAdapter> _vsAdapter; private readonly Mock<IOleCommandTarget> _nextTarget; private readonly Mock<IDisplayWindowBroker> _broker; private readonly Mock<ITextManager> _textManager; private readonly Mock<ICommonOperations> _commonOperations; private readonly Mock<IVimApplicationSettings> _vimApplicationSettings; private readonly IOleCommandTarget _target; private readonly VsCommandTarget _targetRaw; private readonly IVimBufferCoordinator _bufferCoordinator; protected VsCommandTargetTest(bool isReSharperInstalled) { _textView = CreateTextView(""); _textBuffer = _textView.TextBuffer; _vimBuffer = Vim.CreateVimBuffer(_textView); _bufferCoordinator = new VimBufferCoordinator(_vimBuffer); _vim = _vimBuffer.Vim; _factory = new MockRepository(MockBehavior.Strict); _nextTarget = _factory.Create<IOleCommandTarget>(MockBehavior.Strict); _vsAdapter = _factory.Create<IVsAdapter>(); _vsAdapter.SetupGet(x => x.KeyboardDevice).Returns(InputManager.Current.PrimaryKeyboardDevice); _vsAdapter.Setup(x => x.InAutomationFunction).Returns(false); _vsAdapter.Setup(x => x.InDebugMode).Returns(false); _vsAdapter.Setup(x => x.IsIncrementalSearchActive(It.IsAny<ITextView>())).Returns(false); _broker = _factory.Create<IDisplayWindowBroker>(MockBehavior.Loose); _textManager = _factory.Create<ITextManager>(); _commonOperations = _factory.Create<ICommonOperations>(); _vimApplicationSettings = _factory.Create<IVimApplicationSettings>(); var commandTargets = new List<ICommandTarget>(); if (isReSharperInstalled) { commandTargets.Add(ReSharperKeyUtil.GetOrCreate(_bufferCoordinator)); } commandTargets.Add(new StandardCommandTarget( _bufferCoordinator, _textManager.Object, _commonOperations.Object, _broker.Object, _nextTarget.Object)); var oldCommandFilter = _nextTarget.Object; _targetRaw = new VsCommandTarget( _bufferCoordinator, _textManager.Object, _vsAdapter.Object, _broker.Object, KeyUtil, _vimApplicationSettings.Object, _nextTarget.Object, commandTargets.ToReadOnlyCollectionShallow()); _target = _targetRaw; } /// <summary> /// Make sure to clear the KeyMap map on tear down so we don't mess up other tests /// </summary> public override void Dispose() { base.Dispose(); _vim.GlobalKeyMap.ClearKeyMappings(); } /// <summary> /// Run the KeyInput value through Exec /// </summary> protected void RunExec(KeyInput keyInput) { Assert.True(OleCommandUtil.TryConvert(keyInput, out OleCommandData data)); try { _target.Exec(data); } finally { data.Dispose(); } } protected void RunExec(VimKey vimKey) { RunExec(KeyInputUtil.VimKeyToKeyInput(vimKey)); } /// <summary> /// Run the given command as a type char through the Exec function /// </summary> protected void RunExec(char c) { var keyInput = KeyInputUtil.CharToKeyInput(c); RunExec(keyInput); } internal void RunExec(EditCommand editCommand) { var oleCommandData = OleCommandData.Empty; try { Assert.True(OleCommandUtil.TryConvert(editCommand, out oleCommandData)); _target.Exec(oleCommandData); } finally { oleCommandData.Dispose(); } DoEvents(); } /// <summary> /// Run the KeyInput value through QueryStatus. Returns true if the QueryStatus call /// indicated the command was supported /// </summary> protected bool RunQueryStatus(KeyInput keyInput) { Assert.True(OleCommandUtil.TryConvert(keyInput, out OleCommandData data)); try { return ErrorHandler.Succeeded(_target.QueryStatus(data, out OLECMD command)) && command.cmdf == (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); } finally { data.Dispose(); } } /// <summary> /// Run the char through the QueryStatus method /// </summary> protected bool RunQueryStatus(char c) { var keyInput = KeyInputUtil.CharToKeyInput(c); return RunQueryStatus(keyInput); } internal static EditCommand CreateEditCommand(EditCommandKind editCommandKind) { return new EditCommand(KeyInputUtil.CharToKeyInput('i'), editCommandKind, Guid.Empty, 42); } public sealed class TryCustomProcessTest : VsCommandTargetTest { public TryCustomProcessTest() : base(isReSharperInstalled: false) { _vimBuffer.LocalSettings.SoftTabStop = 4; _vimApplicationSettings.SetupGet(x => x.CleanMacros).Returns(false); } [WpfFact] public void BackNoSoftTabStop() { _nextTarget.SetupExecOne().Verifiable(); _vimApplicationSettings.SetupGet(x => x.UseEditorTabAndBackspace).Returns(true); Assert.True(_targetRaw.TryCustomProcess(InsertCommand.Back)); _factory.Verify(); } /// <summary> /// Don't custom process back when 'sts' is enabled, let Vim handle it /// </summary> [WpfFact] public void BackSoftTabStop() { _vimApplicationSettings.SetupGet(x => x.UseEditorTabAndBackspace).Returns(false); Assert.False(_targetRaw.TryCustomProcess(InsertCommand.Back)); } [WpfFact] public void TabNoSoftTabStop() { _vimApplicationSettings.SetupGet(x => x.UseEditorTabAndBackspace).Returns(true); _nextTarget.SetupExecOne().Verifiable(); Assert.True(_targetRaw.TryCustomProcess(InsertCommand.InsertTab)); _factory.Verify(); } /// <summary> /// Don't custom process tab when 'sts' is enabled, let Vim handle it /// </summary> [WpfFact] public void TabSoftTabStop() { _vimApplicationSettings.SetupGet(x => x.UseEditorTabAndBackspace).Returns(false); _vimBuffer.LocalSettings.SoftTabStop = 4; Assert.False(_targetRaw.TryCustomProcess(InsertCommand.InsertTab)); } /// <summary> /// Don't custom process anything when doing clean macro recording. Let core vim /// handle it all so we don't affect the output with intellisense. /// </summary> [WpfFact] public void CleanMacrosRecording() { try { _vim.MacroRecorder.StartRecording(UnnamedRegister, isAppend: false); _vimApplicationSettings.SetupGet(x => x.CleanMacros).Returns(true); _vimApplicationSettings.SetupGet(x => x.UseEditorTabAndBackspace).Returns(false); Assert.False(_targetRaw.TryCustomProcess(InsertCommand.InsertTab)); Assert.False(_targetRaw.TryCustomProcess(InsertCommand.Back)); } finally { _vim.MacroRecorder.StopRecording(); } } [WpfFact] public void CleanMacrosNotRecording() { _nextTarget.SetupExecOne(); _vimApplicationSettings.SetupGet(x => x.CleanMacros).Returns(true); _vimApplicationSettings.SetupGet(x => x.UseEditorTabAndBackspace).Returns(true); Assert.False(_vim.MacroRecorder.IsRecording); Assert.True(_targetRaw.TryCustomProcess(InsertCommand.InsertTab)); Assert.True(_targetRaw.TryCustomProcess(InsertCommand.Back)); } } public sealed class TryConvertTest : VsCommandTargetTest { public TryConvertTest() : base(isReSharperInstalled: false) { } private void AssertCannotConvert2K(VSConstants.VSStd2KCmdID id) { Assert.False(_targetRaw.TryConvert(VSConstants.VSStd2K, (uint)id, IntPtr.Zero, out KeyInput ki)); } private void AssertCanConvert2K(VSConstants.VSStd2KCmdID id, KeyInput expected) { Assert.True(_targetRaw.TryConvert(VSConstants.VSStd2K, (uint)id, IntPtr.Zero, out KeyInput ki)); Assert.Equal(expected, ki); } [WpfFact] public void Tab() { AssertCanConvert2K(VSConstants.VSStd2KCmdID.TAB, KeyInputUtil.TabKey); } [WpfFact] public void InAutomationShouldFail() { _vsAdapter.Setup(x => x.InAutomationFunction).Returns(true); AssertCannotConvert2K(VSConstants.VSStd2KCmdID.TAB); } [WpfFact] public void InIncrementalSearchShouldFail() { _vsAdapter.Setup(x => x.IsIncrementalSearchActive(It.IsAny<ITextView>())).Returns(true); AssertCannotConvert2K(VSConstants.VSStd2KCmdID.TAB); } } public sealed class QueryStatusTest : VsCommandTargetTest { public QueryStatusTest() : base(isReSharperInstalled: false) { } [WpfFact] public void IgnoreEscapeIfCantProcess() { _vimBuffer.SwitchMode(ModeKind.Disabled, ModeArgument.None); Assert.False(_vimBuffer.CanProcess(KeyInputUtil.EscapeKey)); _nextTarget.SetupQueryStatus().Verifiable(); RunQueryStatus(KeyInputUtil.EscapeKey); _factory.Verify(); } [WpfFact] public void EnableEscapeButDontHandleNormally() { _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); Assert.True(_vimBuffer.CanProcess(VimKey.Escape)); Assert.True(RunQueryStatus(KeyInputUtil.EscapeKey)); } } public sealed class ExecTest : VsCommandTargetTest { public ExecTest() : base(isReSharperInstalled: false) { } [WpfFact] public void PassOnIfCantHandle() { _vimBuffer.SwitchMode(ModeKind.Disabled, ModeArgument.None); Assert.False(_vimBuffer.CanProcess(VimKey.Enter)); _nextTarget.SetupExecOne().Verifiable(); RunExec(KeyInputUtil.EnterKey); _factory.Verify(); } /// <summary> /// If a given KeyInput is marked for discarding make sure we don't pass it along to the /// next IOleCommandTarget. /// </summary> [WpfFact] public void DiscardedKeyInput() { _bufferCoordinator.Discard(KeyInputUtil.EscapeKey); RunExec(KeyInputUtil.EscapeKey); _factory.Verify(); } [WpfFact] public void HandleEscapeNormally() { var count = 0; _vimBuffer.KeyInputProcessed += delegate { count++; }; _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); RunExec(KeyInputUtil.EscapeKey); Assert.Equal(1, count); } [WpfFact] - public void DiscardUnprocessedInputInNonInputMode() + public void DiscardUnprocessedInput_Visual() { _commonOperations.Setup(x => x.Beep()).Verifiable(); _vimBuffer.SwitchMode(ModeKind.VisualCharacter, ModeArgument.None); RunExec(KeyInputUtil.CharToKeyInput('¤')); _commonOperations.Verify(); } /// <summary> - /// Must be able discard non-ASCII characters or they will end up - /// as input + /// Must discard non-ASCII characters in normal mode or they + /// will end up as input /// </summary> [WpfTheory] [InlineData('¤')] [InlineData('¨')] [InlineData('£')] [InlineData('§')] [InlineData('´')] - public void CanProcessPrintableNonAscii(char c) + public void DiscardUnprocessedInput_Normal(char c) { // Reported in issue #1793. _commonOperations.Setup(x => x.Beep()).Verifiable(); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); RunExec(KeyInputUtil.CharToKeyInput(c)); _commonOperations.Verify(); } /// <summary> /// If there is buffered KeyInput values then the provided KeyInput shouldn't ever be /// directly handled by the VsCommandTarget or the next IOleCommandTarget in the /// chain. It should be passed directly to the IVimBuffer if it can be handled else /// it shouldn't be handled /// </summary> [WpfFact] public void WithUnmatchedBufferedInput() { _vim.GlobalKeyMap.AddKeyMapping("jj", "hello", allowRemap: false, KeyRemapMode.Insert); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); RunExec('j'); Assert.False(_vimBuffer.BufferedKeyInputs.IsEmpty); RunExec('a'); Assert.Equal("ja", _textView.GetLine(0).GetText()); Assert.True(_vimBuffer.BufferedKeyInputs.IsEmpty); } /// <summary> /// Make sure in the case that the next input matches the final expansion of a /// buffered input that it's processed correctly /// </summary> [WpfFact] public void WithMatchedBufferedInput() { _vim.GlobalKeyMap.AddKeyMapping("jj", "hello", allowRemap: false, KeyRemapMode.Insert); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); RunExec('j'); Assert.False(_vimBuffer.BufferedKeyInputs.IsEmpty); RunExec('j'); Assert.Equal("hello", _textView.GetLine(0).GetText()); Assert.True(_vimBuffer.BufferedKeyInputs.IsEmpty); } /// <summary> /// In the case where there is buffered KeyInput values and the next KeyInput collapses /// it into a single value then we need to make sure we pass both values onto the IVimBuffer /// so the remapping can occur /// </summary> [WpfFact] public void CollapseBufferedInputToSingleKeyInput() { _vim.GlobalKeyMap.AddKeyMapping("jj", "z", allowRemap: false, KeyRemapMode.Insert); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); RunExec('j'); Assert.False(_vimBuffer.BufferedKeyInputs.IsEmpty); RunExec('j'); Assert.Equal("z", _textView.GetLine(0).GetText()); Assert.True(_vimBuffer.BufferedKeyInputs.IsEmpty); } /// <summary> /// If parameter info is up then the arrow keys should be routed to parameter info and /// not to the IVimBuffer /// </summary> [WpfFact] public void SignatureHelp_ArrowGoToCommandTarget() { _broker.SetupGet(x => x.IsSignatureHelpActive).Returns(true); var count = 0; _nextTarget.SetupExecOne().Callback(() => { count++; }); foreach (var key in new[] { VimKey.Down, VimKey.Up }) { RunExec(VimKey.Down); } Assert.Equal(2, count); } /// <summary> /// Make sure the GoToDefinition command wil clear the active selection. We don't want /// this command causing VsVim to switch to Visual Mode /// </summary> [WpfFact] public void GoToDefinitionShouldClearSelection() { _textBuffer.SetText("dog", "cat", "bear"); _textView.MoveCaretToLine(0); // Return our text view in the list of text views to check for new selections. _textManager.Setup(x => x.GetDocumentTextViews(DocumentLoad.RespectLazy)).Returns(new[] { _textView }); // Set up a command target to select text in the text buffer. var commandGroup = VSConstants.GUID_VSStandardCommandSet97; _nextTarget.Setup(x => x.Exec( ref commandGroup, It.IsAny<uint>(), It.IsAny<uint>(), It.IsAny<IntPtr>(), It.IsAny<IntPtr>())).Returns(() => { _textView.Selection.Select(_textBuffer.GetLineSpan(1, 3)); return VSConstants.S_OK; }); Assert.Equal(_textView.GetLine(0).Start, _textView.GetCaretPoint()); RunExec(CreateEditCommand(EditCommandKind.GoToDefinition)); Assert.True(_textView.Selection.IsEmpty); Assert.Equal(_textView.GetLine(1).Start, _textView.GetCaretPoint()); } /// <summary> /// The IOleCommandTarget code has logic for allowing intellisense control keys to go directly /// to the next IOleCommandTarget. For instance if completion is active let Left, Right, etc /// go to the next target. /// /// This logic only works though when we know what the mapped key is. That is if the user typed /// 'j' but it mapped to Left then Left is what needs to be considered, not 'j'. In the case the /// mapping is incomplete or doesn't mapp to a single key then there isn't really anything we can /// do other than forward directly to the <see cref="IVimBuffer"/> instance. /// /// Issue 1855 /// </summary> [WpfFact] public void NonSingleKeyMapShouldNotDismissIntellisense() { _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("jj", "<ESC>", allowRemap: true, KeyRemapMode.Insert); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); _vimBuffer.Process("j"); Assert.Equal(1, _vimBuffer.BufferedKeyInputs.Length); var didDismiss = false; _broker.Setup(x => x.IsCompletionActive).Returns(true); _broker.Setup(x => x.DismissDisplayWindows()).Callback(() => didDismiss = true); RunExec('k'); Assert.False(didDismiss); Assert.Equal(ModeKind.Insert, _vimBuffer.ModeKind); Assert.Equal("jk", _textBuffer.GetLine(0).GetText()); } [WpfFact] public void EnsureTabPassedToCustomProcessorInComplexKeyMapping() { _vimBuffer.Vim.GlobalKeyMap.AddKeyMapping("jj", "<ESC>", allowRemap: true, KeyRemapMode.Insert); _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); _vimBuffer.Process("j"); Assert.Equal(1, _vimBuffer.BufferedKeyInputs.Length); var didDismiss = false; _broker.Setup(x => x.IsCompletionActive).Returns(true); _broker.Setup(x => x.DismissDisplayWindows()).Callback(() => didDismiss = true); var sawChar1 = false; var sawChar2 = false; VimHost.TryCustomProcessFunc += (textView, command) => { if (!sawChar1 && !sawChar2) { Assert.True(command.IsInsert('j')); sawChar1 = true; } else if (sawChar1 && !sawChar2) { Assert.True(command.IsInsertTab); sawChar2 = true; } else { Assert.True(false, "Unexpected character"); } return false; }; RunExec(KeyInputUtil.TabKey); Assert.False(didDismiss); Assert.Equal(ModeKind.Insert, _vimBuffer.ModeKind); Assert.Equal("j\t", _textBuffer.GetLine(0).GetText()); Assert.True(sawChar1 && sawChar2); } } public sealed class ExecCoreTest : VsCommandTargetTest { public ExecCoreTest() : base(isReSharperInstalled: false) { } /// <summary> /// Don't process GoToDefinition even if it has a KeyInput associated with it. In the past /// a bug in OleCommandTarget.Convert created an EditCommand in this state. That is a bug /// that should be fixed but also there is simply no reason that we should be processing this /// command here. Let VS do the work /// </summary> [WpfFact] public void GoToDefinition() { var editCommand = CreateEditCommand(EditCommandKind.GoToDefinition); Assert.False(_targetRaw.Exec(editCommand, out Action preAction, out Action postAction)); } } public sealed class ReSharperQueryStatusTest : VsCommandTargetTest { public ReSharperQueryStatusTest() : base(isReSharperInstalled: true) { } /// Don't actually run the Escape in the QueryStatus command if we're in visual mode /// </summary> [WpfFact] public void EnableEscapeAndDontHandleInResharperPlusVisualMode() { var count = 0; _vimBuffer.KeyInputProcessed += delegate { count++; }; _vimBuffer.SwitchMode(ModeKind.VisualCharacter, ModeArgument.None); RunQueryStatus(KeyInputUtil.EscapeKey); Assert.Equal(0, count); } /// <summary> /// Make sure we process Escape during QueryStatus if we're in insert mode and still pass /// it on to R#. R# will intercept escape and never give it to us and we'll think /// we're still in insert. /// </summary> [WpfFact] public void EnableAndHandleEscape() { var count = 0; _vimBuffer.KeyInputProcessed += delegate { count++; }; _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); Assert.True(RunQueryStatus(KeyInputUtil.EscapeKey)); Assert.True(_bufferCoordinator.IsDiscarded(KeyInputUtil.EscapeKey)); Assert.Equal(1, count); } /// <summary> /// When Back is processed as a command make sure we handle it in QueryStatus and hide /// it from R#. Back in R# is used to do special parens delete and we don't want that /// overriding a command /// </summary> [WpfFact] public void BackspaceAsCommand() { var backKeyInput = KeyInputUtil.VimKeyToKeyInput(VimKey.Back); var count = 0; _vimBuffer.KeyInputProcessed += delegate { count++; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(_vimBuffer.CanProcessAsCommand(backKeyInput)); Assert.False(RunQueryStatus(backKeyInput)); Assert.True(_bufferCoordinator.IsDiscarded(backKeyInput)); Assert.Equal(1, count); } /// <summary> /// When Back is processed as an edit make sure we don't special case it and instead let /// it go back to R# for processing. They special case Back during edit to do actions /// like matched paren deletion that we want to enable. /// </summary> [WpfFact] public void BackspaceInInsert() { var backKeyInput = KeyInputUtil.VimKeyToKeyInput(VimKey.Back); var count = 0; _vimBuffer.KeyInputProcessed += delegate { count++; }; _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); Assert.True(_vimBuffer.CanProcessAsCommand(backKeyInput)); Assert.True(RunQueryStatus(backKeyInput)); Assert.False(_bufferCoordinator.HasDiscardedKeyInput); Assert.Equal(0, count); } /// <summary> /// Make sure we process Escape during QueryStatus if we're in insert mode. R# will /// intercept escape and never give it to us and we'll think we're still in insert /// </summary> [WpfFact] public void EnableAndHandleEscapeInResharperPlusExternalEdit() { var count = 0; _vimBuffer.KeyInputProcessed += delegate { count++; }; _vimBuffer.SwitchMode(ModeKind.ExternalEdit, ModeArgument.None); Assert.True(RunQueryStatus(KeyInputUtil.EscapeKey)); Assert.True(_bufferCoordinator.IsDiscarded(KeyInputUtil.EscapeKey)); Assert.Equal(1, count); } /// <summary> /// The PageUp key isn't special so don't special case it in R# /// </summary> [WpfFact] public void HandlePageUpNormally() { var count = 0; _vimBuffer.KeyInputProcessed += delegate { count++; }; _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(RunQueryStatus(KeyInputUtil.VimKeyToKeyInput(VimKey.PageUp))); Assert.Equal(0, count); } /// <summary> /// When Visual Studio is in debug mode R# will attempt to handle the Enter key directly /// and do nothing. Presumably they are doing this because it is an edit command and they /// are suppressing it's action. We want to process this directly though if Vim believes /// Enter to be a command and not an edit, for example in normal mode /// </summary> [WpfFact] public void EnterAsCommand() { _textView.SetText("cat", "dog"); _textView.MoveCaretTo(0); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); Assert.True(_vimBuffer.CanProcessAsCommand(KeyInputUtil.EnterKey)); Assert.False(RunQueryStatus(KeyInputUtil.EnterKey)); Assert.Equal(_textView.GetLine(1).Start, _textView.GetCaretPoint()); Assert.True(_bufferCoordinator.IsDiscarded(KeyInputUtil.EnterKey)); } /// <summary> /// If Enter isn't going to be processed as a command then don't special case it /// mode for R#. It would be an edit and we don't want to interfere with R#'s handling /// of edits /// </summary> [WpfFact] public void EnterInInsert() { _textView.SetText("cat", "dog"); _textView.MoveCaretTo(0); var savedSnapshot = _textView.TextSnapshot; _vimBuffer.SwitchMode(ModeKind.Insert, ModeArgument.None); Assert.True(_vimBuffer.CanProcessAsCommand(KeyInputUtil.EnterKey)); Assert.True(RunQueryStatus(KeyInputUtil.EnterKey)); Assert.False(_bufferCoordinator.HasDiscardedKeyInput); Assert.Equal(_textView.GetLine(0).Start, _textView.GetCaretPoint()); Assert.Same(savedSnapshot, _textView.TextSnapshot); } } } }
VsVim/VsVim
652382a7905c607c530822db5e717bed3c8463fb
Improve variable name
diff --git a/Src/VimCore/RegisterMap.fs b/Src/VimCore/RegisterMap.fs index 2ba96d2..e8c032d 100644 --- a/Src/VimCore/RegisterMap.fs +++ b/Src/VimCore/RegisterMap.fs @@ -1,135 +1,135 @@ #light namespace Vim /// IRegisterValueBacking implementation for the clipboard type ClipboardRegisterValueBacking (_device: IClipboardDevice) = - let mutable _value = RegisterValue(StringUtil.Empty, OperationKind.CharacterWise) + let mutable _lastSetValue = RegisterValue(StringUtil.Empty, OperationKind.CharacterWise) member x.RegisterValue = let text = _device.Text - if text = _value.StringValue then - _value + if text = _lastSetValue.StringValue then + _lastSetValue else let operationKind = if EditUtil.GetLineBreakLengthAtEnd text > 0 then OperationKind.LineWise else OperationKind.CharacterWise RegisterValue(text, operationKind) member x.SetRegisterValue (value: RegisterValue) = - _value <- value + _lastSetValue <- value _device.Text <- value.StringValue interface IRegisterValueBacking with member x.RegisterValue with get () = x.RegisterValue and set value = x.SetRegisterValue value /// IRegisterValueBacking implementation for append registers. All of the lower /// case letter registers can be accessed via an upper case version. The only /// difference is when accessed via upper case sets of the value should be /// append operations type AppendRegisterValueBacking (_register: Register) = interface IRegisterValueBacking with member x.RegisterValue with get () = _register.RegisterValue and set value = _register.RegisterValue <- _register.RegisterValue.Append value type LastSearchRegisterValueBacking (_vimData: IVimData) = interface IRegisterValueBacking with member x.RegisterValue with get () = RegisterValue(_vimData.LastSearchData.Pattern, OperationKind.CharacterWise) and set value = _vimData.LastSearchData <- SearchData(value.StringValue, SearchPath.Forward, false) type CommandLineBacking (_vimData: IVimData) = interface IRegisterValueBacking with member x.RegisterValue with get() = RegisterValue(_vimData.LastCommandLine, OperationKind.CharacterWise) and set _ = () type LastTextInsertBacking (_vimData: IVimData) = interface IRegisterValueBacking with member x.RegisterValue with get() = let value = match _vimData.LastTextInsert with Some s -> s | None -> "" RegisterValue(value, OperationKind.CharacterWise) and set _ = () type internal BlackholeRegisterValueBacking() = let mutable _value = RegisterValue(StringUtil.Empty, OperationKind.CharacterWise) interface IRegisterValueBacking with member x.RegisterValue with get() = _value and set _ = () type internal RegisterMap (_map: Map<RegisterName, Register>) = new(vimData: IVimData, clipboard: IClipboardDevice, currentFileNameFunc: unit -> string option) = let clipboardBacking = ClipboardRegisterValueBacking(clipboard) :> IRegisterValueBacking let commandLineBacking = CommandLineBacking(vimData) :> IRegisterValueBacking let lastTextInsertBacking = LastTextInsertBacking(vimData) :> IRegisterValueBacking let fileNameBacking = { new IRegisterValueBacking with member x.RegisterValue with get() = let text = match currentFileNameFunc() with | None -> StringUtil.Empty | Some(str) -> str RegisterValue(text, OperationKind.CharacterWise) and set _ = () } // Is this an append register let isAppendRegister (name: RegisterName) = name.IsAppend let getBacking name = match name with | RegisterName.SelectionAndDrop SelectionAndDropRegister.Plus -> clipboardBacking | RegisterName.SelectionAndDrop SelectionAndDropRegister.Star -> clipboardBacking | RegisterName.ReadOnly ReadOnlyRegister.Percent -> fileNameBacking | RegisterName.ReadOnly ReadOnlyRegister.Colon -> commandLineBacking | RegisterName.ReadOnly ReadOnlyRegister.Dot -> lastTextInsertBacking | RegisterName.Blackhole -> BlackholeRegisterValueBacking() :> IRegisterValueBacking | RegisterName.LastSearchPattern -> LastSearchRegisterValueBacking(vimData) :> IRegisterValueBacking | _ -> DefaultRegisterValueBacking() :> IRegisterValueBacking // Create the map without the append registers let map = RegisterName.All |> Seq.filter (fun name -> not (isAppendRegister name)) |> Seq.map (fun n -> n, Register(n, getBacking n)) |> Map.ofSeq // Now that the map has all of the append registers backing add the actual append // registers let map = let originalMap = map RegisterName.All |> Seq.filter isAppendRegister |> Seq.fold (fun map (name: RegisterName) -> match name.Char with | None -> map | Some c -> let c = CharUtil.ToLower c match NamedRegister.OfChar c |> Option.map RegisterName.Named with | None -> map | Some backingRegisterName -> let backingRegister = Map.find backingRegisterName map let value = AppendRegisterValueBacking(backingRegister) let register = Register(name, value) Map.add name register map) originalMap RegisterMap(map) member x.GetRegister name = Map.find name _map member x.SetRegisterValue name value = let register = x.GetRegister name register.RegisterValue <- value interface IRegisterMap with member x.RegisterNames = _map |> Seq.map (fun pair -> pair.Key) member x.GetRegister name = x.GetRegister name member x.SetRegisterValue name value = x.SetRegisterValue name value
VsVim/VsVim
7c3008739d049685989c7c28075e83b6b4b20c8d
Use VsVim margin for non-relative line numbers
diff --git a/Src/VimCore/LineNumbersMarginOptions.fs b/Src/VimCore/LineNumbersMarginOptions.fs deleted file mode 100644 index 24d8789..0000000 --- a/Src/VimCore/LineNumbersMarginOptions.fs +++ /dev/null @@ -1,21 +0,0 @@ -#light - -namespace Vim -open Microsoft.VisualStudio.Text.Editor -open System.ComponentModel.Composition - -module LineNumbersMarginOptions = - - [<Literal>] - let LineNumbersMarginOptionName = "VsVimLineNumbersMarginOption" - - let LineNumbersMarginOptionId = new EditorOptionKey<bool>(LineNumbersMarginOptionName) - -[<Export(typeof<EditorOptionDefinition>)>] -[<Sealed>] -type public VsVimLineNumbersMarginOption() = - inherit EditorOptionDefinition<bool>() - override x.Default - with get() = false - override x.Key - with get() = LineNumbersMarginOptions.LineNumbersMarginOptionId diff --git a/Src/VimCore/MefInterfaces.fs b/Src/VimCore/MefInterfaces.fs index 9514c99..9888ed5 100644 --- a/Src/VimCore/MefInterfaces.fs +++ b/Src/VimCore/MefInterfaces.fs @@ -64,595 +64,602 @@ type ITrackingLineColumn = abstract Point: SnapshotPoint option /// Get the point as a VirtualSnapshot point on the current ITextSnapshot abstract VirtualPoint: VirtualSnapshotPoint option /// Get the column as it relates to current Snapshot. abstract Column: SnapshotColumn option /// Get the column as a VirtualSnapshotColumn point on the current ITextSnapshot abstract VirtualColumn: VirtualSnapshotColumn option /// Needs to be called when you are done with the ITrackingLineColumn abstract Close: unit -> unit /// Tracks a VisualSpan across edits to the underlying ITextBuffer. type ITrackingVisualSpan = /// The associated ITextBuffer instance abstract TextBuffer: ITextBuffer /// Get the VisualSpan as it relates to the current ITextSnapshot abstract VisualSpan: VisualSpan option /// Needs to be called when the consumer is finished with the ITrackingVisualSpan abstract Close: unit -> unit /// Tracks a Visual Selection across edits to the underlying ITextBuffer. This tracks both /// the selection area and the caret within the selection type ITrackingVisualSelection = /// The SnapshotPoint for the caret within the current ITextSnapshot abstract CaretPoint: SnapshotPoint option /// The associated ITextBuffer instance abstract TextBuffer: ITextBuffer /// Get the Visual Selection as it relates to the current ITextSnapshot abstract VisualSelection: VisualSelection option /// Needs to be called when the consumer is finished with the ITrackingVisualSpan abstract Close: unit -> unit type IBufferTrackingService = /// Create an ITrackingLineColumn at the given position in the buffer. abstract CreateLineOffset: textBuffer: ITextBuffer -> lineNumber: int -> offset: int -> mode: LineColumnTrackingMode -> ITrackingLineColumn /// Create an ITrackingLineColumn at the given SnaphsotColumn abstract CreateColumn: column: SnapshotColumn -> mode: LineColumnTrackingMode -> ITrackingLineColumn /// Create an ITrackingVisualSpan for the given VisualSpan abstract CreateVisualSpan: visualSpan: VisualSpan -> ITrackingVisualSpan /// Create an ITrackingVisualSelection for the given Visual Selection abstract CreateVisualSelection: visualSelection: VisualSelection -> ITrackingVisualSelection /// Does the given ITextBuffer have any out standing tracking instances abstract HasTrackingItems: textBuffer: ITextBuffer -> bool type IVimBufferCreationListener = /// Called whenever an IVimBuffer is created abstract VimBufferCreated: vimBuffer: IVimBuffer -> unit /// Supports the creation and deletion of folds within a ITextBuffer. Most components /// should talk to IFoldManager directly type IFoldData = /// Associated ITextBuffer the data is over abstract TextBuffer: ITextBuffer /// Gets snapshot spans for all of the currently existing folds. This will /// only return the folds explicitly created by vim. It won't return any /// collapsed regions in the ITextView abstract Folds: SnapshotSpan seq /// Create a fold for the given line range abstract CreateFold: SnapshotLineRange -> unit /// Delete a fold which crosses the given SnapshotPoint. Returns false if /// there was no fold to be deleted abstract DeleteFold: SnapshotPoint -> bool /// Delete all of the folds which intersect the given SnapshotSpan abstract DeleteAllFolds: SnapshotSpan -> unit /// Raised when the collection of folds are updated for any reason [<CLIEvent>] abstract FoldsUpdated: IDelegateEvent<System.EventHandler> /// Supports the creation and deletion of folds within a ITextBuffer /// /// TODO: This should become a merger between folds and outlining regions in /// an ITextBuffer / ITextView type IFoldManager = /// Associated ITextView abstract TextView: ITextView /// Create a fold for the given line range. The fold will be created in a closed state. abstract CreateFold: range: SnapshotLineRange -> unit /// Close 'count' fold values under the given SnapshotPoint abstract CloseFold: point: SnapshotPoint -> count: int -> unit /// Close all folds which intersect the given SnapshotSpan abstract CloseAllFolds: span: SnapshotSpan -> unit /// Delete a fold which crosses the given SnapshotPoint. Returns false if /// there was no fold to be deleted abstract DeleteFold: point: SnapshotPoint -> unit /// Delete all of the folds which intersect the SnapshotSpan abstract DeleteAllFolds: span: SnapshotSpan -> unit /// Toggle fold under the given SnapshotPoint abstract ToggleFold: point: SnapshotPoint -> count: int -> unit /// Toggle all folds under the given SnapshotPoint abstract ToggleAllFolds: span: SnapshotSpan -> unit /// Open 'count' folds under the given SnapshotPoint abstract OpenFold: point: SnapshotPoint -> count: int -> unit /// Open all folds which intersect the given SnapshotSpan abstract OpenAllFolds: span: SnapshotSpan -> unit /// Supports the get and creation of IFoldManager for a given ITextBuffer type IFoldManagerFactory = /// Get the IFoldData for this ITextBuffer abstract GetFoldData: textBuffer: ITextBuffer -> IFoldData /// Get the IFoldManager for this ITextView. abstract GetFoldManager: textView: ITextView -> IFoldManager /// Used because the actual Point class is in WPF which isn't available at this layer. [<Struct>] type VimPoint = { X: double Y: double } /// Abstract representation of the mouse type IMouseDevice = /// Is the left button pressed abstract IsLeftButtonPressed: bool /// Is the right button pressed abstract IsRightButtonPressed: bool /// Get the position of the mouse position within the ITextView abstract GetPosition: textView: ITextView -> VimPoint option /// Is the given ITextView in the middle fo a drag operation? abstract InDragOperation: textView: ITextView -> bool /// Abstract representation of the keyboard type IKeyboardDevice = /// Is the given key pressed abstract IsArrowKeyDown: bool /// The modifiers currently pressed on the keyboard abstract KeyModifiers: VimKeyModifiers /// Tracks changes to the associated ITextView type ILineChangeTracker = /// Swap the most recently changed line with its saved copy abstract Swap: unit -> bool /// Manages the ILineChangeTracker instances type ILineChangeTrackerFactory = /// Get the ILineChangeTracker associated with the given vim buffer information abstract GetLineChangeTracker: vimBufferData: IVimBufferData -> ILineChangeTracker /// Provides access to the system clipboard type IClipboardDevice = /// Whether to report errors that occur when using the clipboard abstract ReportErrors: bool with get, set /// The text contents of the clipboard device abstract Text: string with get, set [<RequireQualifiedAccess>] [<NoComparison>] [<NoEquality>] type Result = | Succeeded | Failed of Error: string [<Flags>] type ViewFlags = | None = 0 /// Ensure the context point is visible in the ITextView | Visible = 0x01 /// If the context point is inside a collapsed region then it needs to be exapnded | TextExpanded = 0x02 /// Using the context point as a reference ensure the scroll respects the 'scrolloff' /// setting | ScrollOffset = 0x04 /// Possibly move the caret to account for the 'virtualedit' setting | VirtualEdit = 0x08 /// Standard flags: /// Visible ||| TextExpanded ||| ScrollOffset | Standard = 0x07 /// All flags /// Visible ||| TextExpanded ||| ScrollOffset ||| VirtualEdit | All = 0x0f [<RequireQualifiedAccess>] [<NoComparison>] type RegisterOperation = | Yank | Delete /// Force the operation to be treated like a big delete even if it's a small one. | BigDelete /// This class abstracts out the operations that are common to normal, visual and /// command mode. It usually contains common edit and movement operations and very /// rarely will deal with caret operations. That is the responsibility of the /// caller type ICommonOperations = /// Run the beep operation abstract Beep: unit -> unit /// Associated IEditorOperations abstract EditorOperations: IEditorOperations /// Associated IEditorOptions abstract EditorOptions: IEditorOptions /// The snapshot point in the buffer under the mouse cursor abstract MousePoint: VirtualSnapshotPoint option /// Associated ITextView abstract TextView: ITextView /// Associated VimBufferData instance abstract VimBufferData: IVimBufferData /// Adjust the ITextView scrolling to account for the 'scrolloff' setting after a move operation /// completes abstract AdjustTextViewForScrollOffset: unit -> unit /// This is the same function as AdjustTextViewForScrollOffsetAtPoint except that it moves the caret /// not the view port. Make the caret consistent with the setting not the display abstract AdjustCaretForScrollOffset: unit -> unit /// Adjust the caret if it is past the end of line and 'virtualedit=onemore' is not set abstract AdjustCaretForVirtualEdit: unit -> unit abstract member CloseWindowUnlessDirty: unit -> unit /// Create a possibly LineWise register value with the specified string value at the given /// point. This is factored out here because a LineWise value in vim should always /// end with a new line but we can't always guarantee the text we are working with /// contains a new line. This normalizes out the process needed to make this correct /// while respecting the settings of the ITextBuffer abstract CreateRegisterValue: point: SnapshotPoint -> stringData: StringData -> operationKind: OperationKind -> RegisterValue /// Delete at least count lines from the buffer starting from the provided line. The /// operation will fail if there aren't at least 'maxCount' lines in the buffer from /// the start point. /// /// This operation is performed against the visual buffer. abstract DeleteLines: startLine: ITextSnapshotLine -> maxCount: int -> registerName: RegisterName option -> unit /// Perform the specified action asynchronously using the scheduler abstract DoActionAsync: action: (unit -> unit) -> unit /// Perform the specified action when the text view is ready abstract DoActionWhenReady: action: (unit -> unit) -> unit /// Ensure the view properties are met at the caret abstract EnsureAtCaret: viewFlags: ViewFlags -> unit /// Ensure the view properties are met at the point abstract EnsureAtPoint: point: SnapshotPoint -> viewFlags: ViewFlags -> unit /// Filter the specified line range through the specified command abstract FilterLines: SnapshotLineRange -> command: string -> unit /// Format the specified line range abstract FormatCodeLines: SnapshotLineRange -> unit /// Format the specified line range abstract FormatTextLines: SnapshotLineRange -> preserveCaretPosition: bool -> unit /// Forward the specified action to the focused window abstract ForwardToFocusedWindow: action: (ICommonOperations -> unit) -> unit /// Get the new line text which should be used for new lines at the given SnapshotPoint abstract GetNewLineText: SnapshotPoint -> string /// Get the register to use based on the name provided to the operation. abstract GetRegister: name: RegisterName option -> Register /// Get the indentation for a newly created ITextSnasphotLine. The context line is /// is provided to calculate the indentation off of /// /// Warning: Calling this API can cause the buffer to be edited. Asking certain /// editor implementations about the indentation, in particular Razor, can cause /// an edit to occur. /// /// Issue #946 abstract GetNewLineIndent: contextLine: ITextSnapshotLine -> newLine: ITextSnapshotLine -> int option /// Get the standard ReplaceData for the given SnapshotPoint abstract GetReplaceData: point: SnapshotPoint -> VimRegexReplaceData /// Get the current number of spaces to caret we are maintaining abstract GetSpacesToCaret: unit -> int /// Get the number of spaces (when tabs are expanded) that is necessary to get to the /// specified point on it's line abstract GetSpacesToPoint: point: SnapshotPoint -> int /// Get the point that visually corresponds to the specified column on its line abstract GetColumnForSpacesOrEnd: contextLine: ITextSnapshotLine -> spaces: int -> SnapshotColumn /// Get the number of spaces (when tabs are expanded) that is necessary to get to the /// specified virtual point on it's line abstract GetSpacesToVirtualColumn: column: VirtualSnapshotColumn -> int /// Get the virtual point that visually corresponds to the specified column on its line abstract GetVirtualColumnForSpaces: contextLine: ITextSnapshotLine -> spaces: int -> VirtualSnapshotColumn /// Attempt to GoToDefinition on the current state of the buffer. If this operation fails, an error message will /// be generated as appropriate abstract GoToDefinition: unit -> Result /// Go to the file named in the word under the cursor abstract GoToFile: unit -> unit /// Go to the file name specified as a paramter abstract GoToFile: string -> unit /// Go to the file named in the word under the cursor in a new window abstract GoToFileInNewWindow: unit -> unit /// Go to the file name specified as a paramter in a new window abstract GoToFileInNewWindow: string -> unit /// Go to the local declaration of the word under the cursor abstract GoToLocalDeclaration: unit -> unit /// Go to the global declaration of the word under the cursor abstract GoToGlobalDeclaration: unit -> unit /// Go to the "count" next tab window in the specified direction. This will wrap /// around abstract GoToNextTab: path: SearchPath -> count: int -> unit /// Go the nth tab. This uses vim's method of numbering tabs which is a 1 based list. Both /// 0 and 1 can be used to access the first tab abstract GoToTab: int -> unit /// Using the specified base folder, go to the tag specified by ident abstract GoToTagInNewWindow: folder: string -> ident: string -> Result /// Convert any virtual spaces into real spaces / tabs based on the current settings. The caret /// will be positioned at the end of that change abstract FillInVirtualSpace: unit -> unit /// Joins the lines in the range abstract Join: SnapshotLineRange -> JoinKind -> unit /// Load a file into a new window, optionally moving the caret to the first /// non-blank on a specific line or to a specific line and column abstract LoadFileIntoNewWindow: file: string -> lineNumber: int option -> columnNumber: int option -> Result /// Move the caret in the specified direction abstract MoveCaret: caretMovement: CaretMovement -> bool /// Move the caret in the specified direction with an arrow key abstract MoveCaretWithArrow: caretMovement: CaretMovement -> bool /// Move the caret to a given point on the screen and ensure the view has the specified /// properties at that point abstract MoveCaretToColumn: column: SnapshotColumn -> viewFlags: ViewFlags -> unit /// Move the caret to a given virtual point on the screen and ensure the view has the specified /// properties at that point abstract MoveCaretToVirtualColumn: column: VirtualSnapshotColumn -> viewFlags: ViewFlags -> unit /// Move the caret to a given point on the screen and ensure the view has the specified /// properties at that point abstract MoveCaretToPoint: point: SnapshotPoint -> viewFlags: ViewFlags -> unit /// Move the caret to a given virtual point on the screen and ensure the view has the specified /// properties at that point abstract MoveCaretToVirtualPoint: point: VirtualSnapshotPoint -> viewFlags: ViewFlags -> unit /// Move the caret to the MotionResult value abstract MoveCaretToMotionResult: motionResult: MotionResult -> unit /// Navigate to the given point which may occur in any ITextBuffer. This will not update the /// jump list abstract NavigateToPoint: VirtualSnapshotPoint -> bool /// Normalize the spaces and tabs in the string abstract NormalizeBlanks: text: string -> spacesToColumn: int -> string /// Normalize the spaces and tabs in the string at the given column in the buffer abstract NormalizeBlanksAtColumn: text: string -> column: SnapshotColumn -> string /// Normalize the spaces and tabs in the string for a new tabstop abstract NormalizeBlanksForNewTabStop: text: string -> spacesToColumn: int -> tabStop: int -> string /// Normalize the set of spaces and tabs into spaces abstract NormalizeBlanksToSpaces: text: string -> spacesToColumn: int -> string /// Display a status message and fit it to the size of the window abstract OnStatusFitToWindow: message: string -> unit /// Open link under caret abstract OpenLinkUnderCaret: unit -> Result /// Put the specified StringData at the given point. abstract Put: SnapshotPoint -> StringData -> OperationKind -> unit /// Raise the error / warning messages for the given SearchResult abstract RaiseSearchResultMessage: SearchResult -> unit /// Record last change start and end positions abstract RecordLastChange: oldSpan: SnapshotSpan -> newSpan: SnapshotSpan -> unit /// Record last yank start and end positions abstract RecordLastYank: span: SnapshotSpan -> unit /// Redo the buffer changes "count" times abstract Redo: count:int -> unit /// Restore spaces to caret, or move to start of line if 'startofline' is set abstract RestoreSpacesToCaret: spacesToCaret: int -> useStartOfLine: bool -> unit /// Scrolls the number of lines given and keeps the caret in the view abstract ScrollLines: ScrollDirection -> count:int -> unit /// Update the register with the specified value abstract SetRegisterValue: name: RegisterName option -> operation: RegisterOperation -> value: RegisterValue -> unit /// Shift the block of lines to the left by shiftwidth * 'multiplier' abstract ShiftLineBlockLeft: SnapshotSpan seq -> multiplier: int -> unit /// Shift the block of lines to the right by shiftwidth * 'multiplier' abstract ShiftLineBlockRight: SnapshotSpan seq -> multiplier: int -> unit /// Shift the given line range left by shiftwidth * 'multiplier' abstract ShiftLineRangeLeft: SnapshotLineRange -> multiplier: int -> unit /// Shift the given line range right by shiftwidth * 'multiplier' abstract ShiftLineRangeRight: SnapshotLineRange -> multiplier: int -> unit /// Sort the given line range abstract SortLines: SnapshotLineRange -> reverseOrder: bool -> SortFlags -> pattern: string option -> unit /// Substitute Command implementation abstract Substitute: pattern: string -> replace: string -> SnapshotLineRange -> flags: SubstituteFlags -> unit /// Toggle the use of typing language characters abstract ToggleLanguage: isForInsert: bool -> unit /// Map the specified point with negative tracking to the current snapshot abstract MapPointNegativeToCurrentSnapshot: point: SnapshotPoint -> SnapshotPoint /// Map the specified point with positive tracking to the current snapshot abstract MapPointPositiveToCurrentSnapshot: point: SnapshotPoint -> SnapshotPoint /// Undo the buffer changes "count" times abstract Undo: count: int -> unit /// Factory for getting ICommonOperations instances type ICommonOperationsFactory = /// Get the ICommonOperations instance for this IVimBuffer abstract GetCommonOperations: IVimBufferData -> ICommonOperations /// This interface is used to prevent the transition from insert to visual mode /// when a selection occurs. In the majority case a selection of text should result /// in a transition to visual mode. In some cases though, C# event handlers being /// the most notable, the best experience is for the buffer to remain in insert /// mode type IVisualModeSelectionOverride = /// Is insert mode preferred for the current state of the buffer abstract IsInsertModePreferred: textView: ITextView -> bool /// What source should the synchronizer use as the original settings? The values /// in the selected source will be copied over the other settings [<RequireQualifiedAccess>] type SettingSyncSource = | Editor | Vim [<Struct>] type SettingSyncData = { EditorOptionKey: string GetEditorValue: IEditorOptions -> SettingValue option - VimSettingName: string - GetVimSettingValue: IVimBuffer -> obj + VimSettingNames: string list + GetVimValue: IVimBuffer -> obj + SetVimValue: IVimBuffer -> SettingValue -> unit IsLocal: bool } with member x.IsWindow = not x.IsLocal member x.GetSettings vimBuffer = SettingSyncData.GetSettingsCore vimBuffer x.IsLocal static member private GetSettingsCore (vimBuffer: IVimBuffer) isLocal = if isLocal then vimBuffer.LocalSettings :> IVimSettings else vimBuffer.WindowSettings :> IVimSettings static member GetBoolValueFunc (editorOptionKey: EditorOptionKey<bool>) = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions editorOptionKey with | None -> None | Some value -> SettingValue.Toggle value |> Some) static member GetNumberValueFunc (editorOptionKey: EditorOptionKey<int>) = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions editorOptionKey with | None -> None | Some value -> SettingValue.Number value |> Some) static member GetStringValue (editorOptionKey: EditorOptionKey<string>) = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions editorOptionKey with | None -> None | Some value -> SettingValue.String value |> Some) static member GetSettingValueFunc name isLocal = (fun (vimBuffer: IVimBuffer) -> let settings = SettingSyncData.GetSettingsCore vimBuffer isLocal match settings.GetSetting name with | None -> null | Some setting -> match setting.Value with | SettingValue.String value -> value :> obj | SettingValue.Toggle value -> box value | SettingValue.Number value -> box value) + static member SetVimValueFunc name isLocal = + fun (vimBuffer: IVimBuffer) value -> + let settings = SettingSyncData.GetSettingsCore vimBuffer isLocal + settings.TrySetValue name value |> ignore + static member Create (key: EditorOptionKey<'T>) (settingName: string) (isLocal: bool) (convertEditorValue: Func<'T, SettingValue>) (convertSettingValue: Func<SettingValue, obj>) = { EditorOptionKey = key.Name GetEditorValue = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions key with | None -> None | Some value -> convertEditorValue.Invoke value |> Some) - VimSettingName = settingName - GetVimSettingValue = (fun vimBuffer -> + VimSettingNames = [settingName] + GetVimValue = (fun vimBuffer -> let settings = SettingSyncData.GetSettingsCore vimBuffer isLocal match settings.GetSetting settingName with | None -> null | Some setting -> convertSettingValue.Invoke setting.Value) + SetVimValue = SettingSyncData.SetVimValueFunc settingName isLocal IsLocal = isLocal } /// This interface is used to synchronize settings between vim settings and the /// editor settings type IEditorToSettingsSynchronizer = /// Begin the synchronization between the editor and vim settings. This will /// start by overwriting the editor settings with the current local ones /// /// This method can be called multiple times for the same IVimBuffer and it /// will only synchronize once abstract StartSynchronizing: vimBuffer: IVimBuffer -> source: SettingSyncSource -> unit abstract SyncSetting: data: SettingSyncData -> unit /// There are some VsVim services which are only valid in specific host environments. These /// services will implement and export this interface. At runtime the identifier can be /// compared to the IVimHost.Identifier to see if it's valid type IVimSpecificService = abstract HostIdentifier: string /// This will look for an export of <see cref="IVimSpecificService"\> that is convertible to /// 'T and return it type IVimSpecificServiceHost = abstract GetService: unit -> 'T option diff --git a/Src/VimCore/Vim.fs b/Src/VimCore/Vim.fs index ea98f2e..7cc1d7e 100644 --- a/Src/VimCore/Vim.fs +++ b/Src/VimCore/Vim.fs @@ -228,766 +228,770 @@ type internal VimBufferFactory let manager = _undoManagerProvider.GetTextBufferUndoManager textBuffer if manager = null then None else manager.TextBufferUndoHistory |> Some UndoRedoOperations(_host, statusUtil, history, _editorOperationsFactoryService) :> IUndoRedoOperations VimTextBuffer(textBuffer, localSettings, _bufferTrackingService, undoRedoOperations, wordUtil, vim) /// Create a VimBufferData instance for the given ITextView and IVimTextBuffer. This is mainly /// used for testing purposes member x.CreateVimBufferData (vimTextBuffer: IVimTextBuffer) (textView: ITextView) = Contract.Requires (vimTextBuffer.TextBuffer = textView.TextBuffer) let vim = vimTextBuffer.Vim let textBuffer = textView.TextBuffer let statusUtil = _statusUtilFactory.GetStatusUtilForView textView let localSettings = vimTextBuffer.LocalSettings let jumpList = JumpList(textView, _bufferTrackingService) :> IJumpList let windowSettings = WindowSettings(vim.GlobalSettings, textView) VimBufferData(vimTextBuffer, textView, windowSettings, jumpList, statusUtil) :> IVimBufferData /// Create an IVimBuffer instance for the provided VimBufferData member x.CreateVimBuffer (vimBufferData: IVimBufferData) = let textView = vimBufferData.TextView let commonOperations = _commonOperationsFactory.GetCommonOperations vimBufferData let incrementalSearch = IncrementalSearch(vimBufferData, commonOperations) :> IIncrementalSearch let capture = MotionCapture(vimBufferData, incrementalSearch) :> IMotionCapture let textChangeTracker = Modes.Insert.TextChangeTracker.GetTextChangeTracker vimBufferData _commonOperationsFactory let lineChangeTracker = _lineChangeTrackerFactory.GetLineChangeTracker vimBufferData let motionUtil = MotionUtil(vimBufferData, commonOperations) :> IMotionUtil let foldManager = _foldManagerFactory.GetFoldManager textView let insertUtil = InsertUtil(vimBufferData, motionUtil, commonOperations) :> IInsertUtil let commandUtil = CommandUtil(vimBufferData, motionUtil, commonOperations, foldManager, insertUtil, _bulkOperations, lineChangeTracker) :> ICommandUtil let bufferRaw = VimBuffer(vimBufferData, incrementalSearch, motionUtil, vimBufferData.VimTextBuffer.WordNavigator, vimBufferData.WindowSettings, commandUtil) let buffer = bufferRaw :> IVimBuffer let vim = vimBufferData.Vim let createCommandRunner kind countKeyRemapMode = CommandRunner(vimBufferData, capture, commandUtil, kind, countKeyRemapMode) :>ICommandRunner let broker = _completionWindowBrokerFactoryService.GetDisplayWindowBroker textView let bufferOptions = _editorOptionsFactoryService.GetOptions(textView.TextBuffer) let visualOptsFactory visualKind = Modes.Visual.SelectionTracker(vimBufferData, incrementalSearch, visualKind) :> Modes.Visual.ISelectionTracker let undoRedoOperations = vimBufferData.UndoRedoOperations let visualModeSeq = VisualKind.All |> Seq.map (fun visualKind -> let tracker = visualOptsFactory visualKind ((Modes.Visual.VisualMode(vimBufferData, commonOperations, motionUtil, visualKind, createCommandRunner visualKind KeyRemapMode.Visual, capture, tracker)) :> IMode) ) let selectModeSeq = VisualKind.All |> Seq.map (fun visualKind -> let tracker = visualOptsFactory visualKind let runner = createCommandRunner visualKind KeyRemapMode.Select Modes.Visual.SelectMode(vimBufferData, commonOperations, motionUtil, visualKind, runner, capture, undoRedoOperations, tracker) :> IMode) |> List.ofSeq let visualModeList = visualModeSeq |> Seq.append selectModeSeq |> List.ofSeq // Normal mode values let editOptions = _editorOptionsFactoryService.GetOptions(textView) let modeList = [ ((Modes.Normal.NormalMode(vimBufferData, commonOperations, motionUtil, createCommandRunner VisualKind.Character KeyRemapMode.Normal, capture, incrementalSearch)) :> IMode) ((Modes.Command.CommandMode(buffer, commonOperations)) :> IMode) ((Modes.Insert.InsertMode(buffer, commonOperations, broker, editOptions, undoRedoOperations, textChangeTracker :> Modes.Insert.ITextChangeTracker, insertUtil, motionUtil, commandUtil, capture, false, _keyboardDevice, _mouseDevice, _wordCompletionSessionFactoryService)) :> IMode) ((Modes.Insert.InsertMode(buffer, commonOperations, broker, editOptions, undoRedoOperations, textChangeTracker, insertUtil, motionUtil, commandUtil, capture, true, _keyboardDevice, _mouseDevice, _wordCompletionSessionFactoryService)) :> IMode) ((Modes.SubstituteConfirm.SubstituteConfirmMode(vimBufferData, commonOperations) :> IMode)) (DisabledMode(vimBufferData) :> IMode) (ExternalEditMode(vimBufferData) :> IMode) ] @ visualModeList modeList |> List.iter (fun m -> bufferRaw.AddMode m) x.SetupInitialMode buffer _statusUtilFactory.InitializeVimBuffer (bufferRaw :> IVimBufferInternal) bufferRaw /// Setup the initial mode for an IVimBuffer member x.SetupInitialMode (vimBuffer: IVimBuffer) = let vimBufferData = vimBuffer.VimBufferData let commonOperations = _commonOperationsFactory.GetCommonOperations(vimBufferData) // The ITextView is initialized and no one has forced the IVimBuffer out of // the uninitialized state. Do the switch now to the correct mode let setupInitialMode () = if vimBuffer.ModeKind = ModeKind.Uninitialized then vimBuffer.SwitchMode vimBufferData.VimTextBuffer.ModeKind ModeArgument.None |> ignore // The mode should be the current mode of the underlying // IVimTextBuffer. This should be as easy as switching the mode on // startup but this is complicated by the initialization of ITextView // instances. They can, and often are, passed to CreateVimBuffer in // an uninitialized state. In that state certain operations like // Select can't be done. Hence we have to delay the mode switch until // the ITextView is fully initialized. commonOperations.DoActionWhenReady setupInitialMode interface IVimBufferFactory with member x.CreateVimTextBuffer textBuffer vim = x.CreateVimTextBuffer textBuffer vim :> IVimTextBuffer member x.CreateVimBufferData vimTextBuffer textView = x.CreateVimBufferData vimTextBuffer textView member x.CreateVimBuffer vimBufferData = x.CreateVimBuffer vimBufferData :> IVimBuffer /// Default implementation of IVim [<Export(typeof<IVim>)>] type internal Vim ( _vimHost: IVimHost, _bufferFactoryService: IVimBufferFactory, _interpreterFactory: IVimInterpreterFactory, _bufferCreationListeners: Lazy<IVimBufferCreationListener> list, _globalSettings: IVimGlobalSettings, _markMap: IMarkMap, _keyMap: IKeyMap, _clipboardDevice: IClipboardDevice, _search: ISearchService, _fileSystem: IFileSystem, _vimData: IVimData, _bulkOperations: IBulkOperations, _variableMap: VariableMap, _editorToSettingSynchronizer: IEditorToSettingsSynchronizer, _statusUtilFactory: IStatusUtilFactory, _commonOperationsFactory: ICommonOperationsFactory, _mouseDevice: IMouseDevice ) as this = /// This key is placed in the ITextView property bag to note that vim buffer creation has /// been suppressed for that specific instance static let ShouldCreateVimBufferKey = obj() /// Key for IVimTextBuffer instances inside of the ITextBuffer property bag let _vimTextBufferKey = obj() /// Holds an IVimBuffer and the DisposableBag for event handlers on the IVimBuffer. This /// needs to be removed when we're done with the IVimBuffer to avoid leaks let _vimBufferMap = Dictionary<ITextView, IVimBuffer * IVimInterpreter * DisposableBag>() let _digraphMap = DigraphMap() :> IDigraphMap /// Holds the active stack of IVimBuffer instances let mutable _activeBufferStack: IVimBuffer list = List.empty /// Holds the recent stack of IVimBuffer instances let mutable _recentBufferStack: IVimBuffer list = List.empty /// Whether or not the vimrc file should be automatically loaded before creating the /// first IVimBuffer instance let mutable _autoLoadDigraphs = true let mutable _autoLoadVimRc = true let mutable _autoLoadSessionData = true let mutable _digraphsAutoLoaded = false let mutable _sessionDataAutoLoaded = false let mutable _isLoadingVimRc = false let mutable _vimRcState = VimRcState.None /// Holds the setting information which was stored when loading the VimRc file. This /// is applied to IVimBuffer instances which are created when there is no active IVimBuffer let mutable _vimRcLocalSettings = LocalSettings(_globalSettings) :> IVimLocalSettings let mutable _vimRcWindowSettings = WindowSettings(_globalSettings) :> IVimWindowSettings /// Whether or not Vim is currently in disabled mode let mutable _isDisabled = false let mutable _fileSystem = _fileSystem let _registerMap = let currentFileNameFunc() = match _activeBufferStack with | [] -> None | h::_ -> h.VimBufferData.CurrentRelativeFilePath RegisterMap(_vimData, _clipboardDevice, currentFileNameFunc) :> IRegisterMap let _recorder = MacroRecorder(_registerMap) /// Add the IMacroRecorder to the list of IVimBufferCreationListeners. let _bufferCreationListeners = let item = Lazy<IVimBufferCreationListener>(fun () -> _recorder :> IVimBufferCreationListener) item :: _bufferCreationListeners do // When the 'history' setting is changed it impacts our history limits. Keep track of // them here // // Up cast here to work around the F# bug which prevents accessing a CLIEvent from // a derived type (_globalSettings :> IVimSettings).SettingChanged |> Event.filter (fun args -> StringUtil.IsEqual args.Setting.Name GlobalSettingNames.HistoryName) |> Event.add (fun _ -> _vimData.SearchHistory.Limit <- _globalSettings.History _vimData.CommandHistory.Limit <- _globalSettings.History) // Notify the IVimHost that IVim is fully created. _vimHost.VimCreated this [<ImportingConstructor>] new( host: IVimHost, bufferFactoryService: IVimBufferFactory, interpreterFactory: IVimInterpreterFactory, bufferTrackingService: IBufferTrackingService, [<ImportMany>] bufferCreationListeners: Lazy<IVimBufferCreationListener> seq, search: ITextSearchService, fileSystem: IFileSystem, clipboard: IClipboardDevice, bulkOperations: IBulkOperations, editorToSettingSynchronizer: IEditorToSettingsSynchronizer, statusUtilFactory: IStatusUtilFactory, commonOperationsFactory: ICommonOperationsFactory, mouseDevice: IMouseDevice) = let markMap = MarkMap(bufferTrackingService) let globalSettings = GlobalSettings() :> IVimGlobalSettings let vimData = VimData(globalSettings) :> IVimData let variableMap = VariableMap() let listeners = bufferCreationListeners |> List.ofSeq Vim( host, bufferFactoryService, interpreterFactory, listeners, globalSettings, markMap :> IMarkMap, KeyMap(globalSettings, variableMap) :> IKeyMap, clipboard, SearchService(search, globalSettings) :> ISearchService, fileSystem, vimData, bulkOperations, variableMap, editorToSettingSynchronizer, statusUtilFactory, commonOperationsFactory, mouseDevice) member x.ActiveBuffer = ListUtil.tryHeadOnly _activeBufferStack member x.ActiveStatusUtil = match x.ActiveBuffer with | Some vimBuffer -> vimBuffer.VimBufferData.StatusUtil | None -> _statusUtilFactory.EmptyStatusUtil member x.AutoLoadDigraphs with get() = _autoLoadDigraphs and set value = _autoLoadDigraphs <- value member x.AutoLoadVimRc with get() = _autoLoadVimRc and set value = _autoLoadVimRc <- value member x.AutoLoadSessionData with get() = _autoLoadSessionData and set value = _autoLoadSessionData <- value member x.FileSystem with get() = _fileSystem and set value = _fileSystem <- value member x.IsDisabled with get() = _isDisabled and set value = let changed = value <> _isDisabled _isDisabled <- value if changed then x.UpdatedDisabledMode() member x.VariableMap = _variableMap member x.VimBuffers = _vimBufferMap.Values |> Seq.map (fun (vimBuffer, _, _) -> vimBuffer) |> List.ofSeq member x.VimRcState with get() = _vimRcState and set value = _vimRcState <- value member x.FocusedBuffer = match _vimHost.GetFocusedTextView() with | None -> None | Some textView -> let found, tuple = _vimBufferMap.TryGetValue(textView) if found then let (vimBuffer, _, _) = tuple Some vimBuffer else None /// Get the IVimLocalSettings which should be the basis for a newly created IVimTextBuffer member x.GetLocalSettingsForNewTextBuffer () = x.MaybeLoadFiles() match x.ActiveBuffer with | Some buffer -> buffer.LocalSettings | None -> _vimRcLocalSettings /// Get the IVimWindowSettings which should be the basis for a newly created IVimBuffer member x.GetWindowSettingsForNewBuffer () = x.MaybeLoadFiles() match x.ActiveBuffer with | Some buffer -> buffer.WindowSettings | None -> _vimRcWindowSettings /// Close all IVimBuffer instances member x.CloseAllVimBuffers() = x.VimBuffers |> List.iter (fun vimBuffer -> if not vimBuffer.IsClosed then vimBuffer.Close()) /// Create an IVimTextBuffer for the given ITextBuffer. If an IVimLocalSettings instance is /// provided then attempt to copy them into the created IVimTextBuffer copy of the /// IVimLocalSettings member x.CreateVimTextBuffer (textBuffer: ITextBuffer) (localSettings: IVimLocalSettings option) = if textBuffer.Properties.ContainsProperty _vimTextBufferKey then invalidArg "textBuffer" Resources.Vim_TextViewAlreadyHasVimBuffer let vimTextBuffer = _bufferFactoryService.CreateVimTextBuffer textBuffer x // Apply the specified local buffer settings match localSettings with | None -> () | Some localSettings -> localSettings.Settings |> Seq.filter (fun s -> not s.IsValueCalculated) |> Seq.iter (fun s -> vimTextBuffer.LocalSettings.TrySetValue s.Name s.Value |> ignore) // Put the IVimTextBuffer into the ITextBuffer property bag so we can query for it in the future textBuffer.Properties.[_vimTextBufferKey] <- vimTextBuffer // If we are currently disabled then the new IVimTextBuffer instance should be disabled // as well if _isDisabled then vimTextBuffer.SwitchMode ModeKind.Disabled ModeArgument.None vimTextBuffer /// Create an IVimBuffer for the given ITextView and associated IVimTextBuffer. This /// will not notify the IVimBufferCreationListener collection about the new /// IVimBuffer member x.CreateVimBufferCore textView (windowSettings: IVimWindowSettings option) = if _vimBufferMap.ContainsKey(textView) then invalidArg "textView" Resources.Vim_TextViewAlreadyHasVimBuffer let vimTextBuffer = x.GetOrCreateVimTextBuffer textView.TextBuffer let vimBufferData = _bufferFactoryService.CreateVimBufferData vimTextBuffer textView let vimBuffer = _bufferFactoryService.CreateVimBuffer vimBufferData // Apply the specified window settings match windowSettings with | None -> () | Some windowSettings -> windowSettings.Settings |> Seq.filter (fun s -> not s.IsValueCalculated) |> Seq.iter (fun s -> vimBuffer.WindowSettings.TrySetValue s.Name s.Value |> ignore) // Setup the handlers for KeyInputStart and KeyInputEnd to accurately track the active // IVimBuffer instance let eventBag = DisposableBag() vimBuffer.KeyInputStart |> Observable.subscribe (fun _ -> _activeBufferStack <- vimBuffer :: _activeBufferStack ) |> eventBag.Add vimBuffer.KeyInputEnd |> Observable.subscribe (fun _ -> _activeBufferStack <- match _activeBufferStack with | h::t -> t | [] -> [] ) |> eventBag.Add // Subscribe to text view focus events. vimBuffer.TextView.GotAggregateFocus |> Observable.subscribe (fun _ -> x.OnFocus vimBuffer) |> eventBag.Add let vimInterpreter = _interpreterFactory.CreateVimInterpreter vimBuffer _fileSystem _vimBufferMap.Add(textView, (vimBuffer, vimInterpreter, eventBag)) if _vimHost.AutoSynchronizeSettings then _editorToSettingSynchronizer.StartSynchronizing vimBuffer SettingSyncSource.Vim vimBuffer member x.RemoveRecentBuffer vimBuffer = _recentBufferStack <- _recentBufferStack |> Seq.filter (fun item -> item <> vimBuffer) |> List.ofSeq member x.OnFocus vimBuffer = x.RemoveRecentBuffer vimBuffer _recentBufferStack <- vimBuffer :: _recentBufferStack let name = _vimHost.GetName vimBuffer.TextBuffer _vimData.FileHistory.Add name /// Create an IVimBuffer for the given ITextView and associated IVimTextBuffer and notify /// the IVimBufferCreationListener collection about it member x.CreateVimBuffer textView windowSettings = let vimBuffer = x.CreateVimBufferCore textView windowSettings _bufferCreationListeners |> Seq.iter (fun x -> x.Value.VimBufferCreated vimBuffer) vimBuffer member x.GetVimInterpreter (vimBuffer: IVimBuffer) = let tuple = _vimBufferMap.TryGetValue vimBuffer.TextView match tuple with | (true, (_, vimInterpreter, _)) -> vimInterpreter | (false, _) -> _interpreterFactory.CreateVimInterpreter vimBuffer _fileSystem member x.GetOrCreateVimTextBuffer textBuffer = let success, vimTextBuffer = x.TryGetVimTextBuffer textBuffer if success then vimTextBuffer else let settings = x.GetLocalSettingsForNewTextBuffer() x.CreateVimTextBuffer textBuffer (Some settings) member x.GetOrCreateVimBuffer textView = let success, vimBuffer = x.TryGetVimBuffer textView if success then vimBuffer else let settings = x.GetWindowSettingsForNewBuffer() x.CreateVimBuffer textView (Some settings) member x.MaybeLoadFiles() = if x.AutoLoadDigraphs && not _digraphsAutoLoaded then DigraphUtil.AddToMap _digraphMap DigraphUtil.DefaultDigraphs _digraphsAutoLoaded <- true // Load registers before loading the vimrc so that // registers that are set in the vimrc "stick". if x.AutoLoadSessionData && not _sessionDataAutoLoaded then x.LoadSessionData() _sessionDataAutoLoaded <- true if x.AutoLoadVimRc then match _vimRcState with | VimRcState.None -> x.LoadVimRc() |> ignore | VimRcState.LoadSucceeded _ -> () | VimRcState.LoadFailed -> () member x.LoadVimRcCore() = Contract.Assert(_isLoadingVimRc) _globalSettings.VimRc <- System.String.Empty _globalSettings.VimRcPaths <- _fileSystem.GetVimRcDirectories() |> String.concat ";" match x.LoadVimRcFileContents() with | None -> _vimRcLocalSettings <- LocalSettings(_globalSettings) _vimRcWindowSettings <- WindowSettings(_globalSettings) _vimRcState <- VimRcState.LoadFailed x.LoadDefaultSettings() | Some (vimRcPath, lines) -> _globalSettings.VimRc <- vimRcPath.FilePath let bag = new DisposableBag() let errorList = List<string>() let textView = _vimHost.CreateHiddenTextView() let mutable createdVimBuffer: IVimBuffer option = None try // For the vimrc IVimBuffer we go straight to the factory methods. We don't want // to notify any consumers that this IVimBuffer is ever created. It should be // transparent to them and showing it just causes confusion. let vimTextBuffer = _bufferFactoryService.CreateVimTextBuffer textView.TextBuffer x let vimBufferData = _bufferFactoryService.CreateVimBufferData vimTextBuffer textView let vimBuffer = _bufferFactoryService.CreateVimBuffer vimBufferData createdVimBuffer <- Some vimBuffer vimBuffer.ErrorMessage |> Observable.subscribe (fun e -> errorList.Add(e.Message)) |> bag.Add // Actually parse and run all of the commands let vimInterpreter = x.GetVimInterpreter vimBuffer vimInterpreter.RunScript(lines) _vimRcLocalSettings <- LocalSettings.Copy vimBuffer.LocalSettings _vimRcWindowSettings <- WindowSettings.Copy vimBuffer.WindowSettings _vimRcState <- VimRcState.LoadSucceeded (vimRcPath, errorList.ToArray()) if errorList.Count <> 0 then VimTrace.TraceError("Errors loading rc file: {0}", vimRcPath.FilePath) VimTrace.TraceError(String.Join(Environment.NewLine, errorList)) finally // Remove the event handlers bag.DisposeAll() // Be careful not to leak the ITextView in the case of an exception textView.Close() // In general it is the responsibility of the host to close IVimBuffer instances when // the corresponding ITextView is closed. In this particular case though we don't actually // inform the host it is created so make sure it gets closed here match createdVimBuffer with | Some vimBuffer -> if not vimBuffer.IsClosed then vimBuffer.Close() | None -> () member x.LoadVimRc() = if _isLoadingVimRc then // Recursive load detected. Bail out VimRcState.LoadFailed else _isLoadingVimRc <- true try x.LoadVimRcCore() finally _isLoadingVimRc <- false + _globalSettings.VimRcLocalSettings <- Some _vimRcLocalSettings + _globalSettings.VimRcWindowSettings <- Some _vimRcWindowSettings + _vimHost.VimRcLoaded _vimRcState _vimRcLocalSettings _vimRcWindowSettings + _vimRcState /// This actually loads the lines of the vimrc that we should be using member x.LoadVimRcFileContents() = _fileSystem.GetVimRcFilePaths() |> Seq.tryPick (fun vimRcPath -> if not (_vimHost.ShouldIncludeRcFile vimRcPath) then None else VimTrace.TraceInfo("Trying rc file: {0}", vimRcPath.FilePath) _fileSystem.ReadAllLines vimRcPath.FilePath |> Option.map (fun lines -> (vimRcPath, lines))) /// Called when there is no vimrc file. Update IVimGlobalSettings to be the appropriate /// value for what the host requests member x.LoadDefaultSettings(): unit = match _vimHost.DefaultSettings with | DefaultSettings.GVim73 -> // Strictly speaking this is not the default for 7.3. However given this is running // on windows there is little sense in disallowing backspace in insert mode as the // out of the box experience. If users truly want that they can put in a vimrc // file that adds it in _globalSettings.Backspace <- "indent,eol,start" | DefaultSettings.GVim74 -> // User-friendly overrides for users without an rc file. // Compare with Vim 7.4 "C:\Program Files (x86)\Vim\_vimrc" _globalSettings.SelectMode <- "mouse,key" _globalSettings.MouseModel <- "popup" _globalSettings.KeyModel <- "startsel,stopsel" _globalSettings.Selection <- "exclusive" _globalSettings.Backspace <- "indent,eol,start" _globalSettings.WhichWrap <- "<,>,[,]" | _ -> _globalSettings.Backspace <- "indent,eol,start" member x.GetSessionDataDirectory() = let filePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) Path.Combine(filePath, "VsVim") member x.GetSessionDataFilePath() = Path.Combine(x.GetSessionDataDirectory(), "vimdata.json") member x.ReadSessionData filePath = // Note: Older session data will not have the 'isMacro' field. // If 'isMacro' is missing, then the value is a string, // which is backward compatible. let filePath= x.GetSessionDataFilePath() match _fileSystem.Read filePath with | None -> SessionData.Empty | Some stream -> try use stream = stream let serializer = new DataContractJsonSerializer(typeof<SessionData>) serializer.ReadObject(stream) :?> SessionData with _ -> SessionData.Empty member x.WriteSessionData (sessionData: SessionData) filePath = let serializer = new DataContractJsonSerializer(typeof<SessionData>) use stream = new MemoryStream() try serializer.WriteObject(stream, sessionData) stream.Position <- 0L _fileSystem.Write filePath stream |> ignore with _ as ex -> VimTrace.TraceError ex member x.LoadSessionDataCore filePath = let sessionData = x.ReadSessionData filePath let registers = if sessionData.Registers = null then [| |] else sessionData.Registers for sessionReg in registers do match sessionReg.Name |> RegisterName.OfChar with | Some name -> let kind = if sessionReg.IsCharacterWise then OperationKind.CharacterWise else OperationKind.LineWise let registerValue = if sessionReg.IsMacro then match KeyNotationUtil.TryStringToKeyInputSet(sessionReg.Value) with | Some keyInputSet -> RegisterValue(keyInputSet.KeyInputs) | None -> RegisterValue(sessionReg.Value, kind) else RegisterValue(sessionReg.Value, kind) _registerMap.SetRegisterValue name registerValue | None -> () member x.LoadSessionData() = // Make sure the VsVim package is loaded so that session data // will be saved on exit (issues #2087 and #1726). _vimHost.EnsurePackageLoaded() x.LoadSessionDataCore (x.GetSessionDataFilePath()) member x.SaveSessionDataCore filePath = let sessionRegisterArray = NamedRegister.All |> Seq.filter (fun n -> not n.IsAppend) |> Seq.map (fun n -> let registerName = RegisterName.Named n let register = _registerMap.GetRegister registerName let registerValue = register.RegisterValue let isMacro = not registerValue.IsString let isCharacterWise = registerValue.OperationKind = OperationKind.CharacterWise let value = if isMacro then registerValue.KeyInputs |> KeyInputSetUtil.OfList |> KeyNotationUtil.KeyInputSetToString else registerValue.StringValue { Name = n.Char; IsCharacterWise = isCharacterWise; Value = value; IsMacro = isMacro; }) |> Seq.toArray let sessionData = { Registers = sessionRegisterArray } x.WriteSessionData sessionData filePath member x.SaveSessionData() = _fileSystem.CreateDirectory (x.GetSessionDataDirectory()) |> ignore x.SaveSessionDataCore (x.GetSessionDataFilePath()) member x.RemoveVimBuffer textView = let found, tuple = _vimBufferMap.TryGetValue(textView) if found then let vimBuffer, _ , bag = tuple x.RemoveRecentBuffer vimBuffer bag.DisposeAll() _vimBufferMap.Remove textView member x.TryGetVimBuffer(textView: ITextView, [<Out>] vimBuffer: IVimBuffer byref) = let tuple = _vimBufferMap.TryGetValue textView match tuple with | (true, (buffer, _, _)) -> vimBuffer <- buffer true | (false, _) -> false /// Determine if an IVimBuffer instance should be created for a given ITextView. If the /// decision to not create an IVimBuffer then this decision is persisted for the lifetime /// of the ITextView. /// /// Allowing it to change in the middle would mean only a portion of the services around /// and IVimBuffer were created and hence it would just appear buggy to the user. /// /// Also we want to reduce the number of times we ask the host this question. The determination /// could be expensive and there is no need to do it over and over again. Scenarios like /// the command window end up forcing this code path a large number of times. member x.ShouldCreateVimBuffer (textView: ITextView) = match PropertyCollectionUtil.GetValue<bool> ShouldCreateVimBufferKey textView.Properties with | Some value -> value | None -> let value = _vimHost.ShouldCreateVimBuffer textView textView.Properties.AddProperty(ShouldCreateVimBufferKey, (box value)) value member x.TryGetOrCreateVimBufferForHost(textView: ITextView, [<Out>] vimBuffer: IVimBuffer byref) = if x.TryGetVimBuffer(textView, &vimBuffer) then true elif x.ShouldCreateVimBuffer textView then let settings = x.GetWindowSettingsForNewBuffer() vimBuffer <- x.CreateVimBuffer textView (Some settings) true else false member x.TryGetVimTextBuffer (textBuffer: ITextBuffer, [<Out>] vimTextBuffer: IVimTextBuffer byref) = match PropertyCollectionUtil.GetValue<IVimTextBuffer> _vimTextBufferKey textBuffer.Properties with | Some found -> vimTextBuffer <- found true | None -> false /// Get the nth most recent vim buffer member x.TryGetRecentBuffer (n: int) = if n >= _recentBufferStack.Length then None else _recentBufferStack |> Seq.skip n |> Seq.head |> Some member x.DisableVimBuffer (vimBuffer: IVimBuffer) = vimBuffer.SwitchMode ModeKind.Disabled ModeArgument.None |> ignore member x.EnableVimBuffer (vimBuffer: IVimBuffer) = let modeKind = if vimBuffer.TextView.Selection.IsEmpty then ModeKind.Normal elif Util.IsFlagSet _globalSettings.SelectModeOptions SelectModeOptions.Mouse then ModeKind.SelectCharacter else ModeKind.VisualCharacter vimBuffer.SwitchMode modeKind ModeArgument.None |> ignore /// Toggle disabled mode for all active IVimBuffer instances to sync up with the current /// state of _isDisabled member x.UpdatedDisabledMode() = if _isDisabled then x.VimBuffers |> Seq.filter (fun vimBuffer -> vimBuffer.Mode.ModeKind <> ModeKind.Disabled) |> Seq.iter x.DisableVimBuffer else x.VimBuffers |> Seq.filter (fun vimBuffer -> vimBuffer.Mode.ModeKind = ModeKind.Disabled) |> Seq.iter x.EnableVimBuffer interface IVim with member x.ActiveBuffer = x.ActiveBuffer member x.ActiveStatusUtil = x.ActiveStatusUtil member x.AutoLoadDigraphs with get() = x.AutoLoadDigraphs and set value = x.AutoLoadDigraphs <- value member x.AutoLoadVimRc with get() = x.AutoLoadVimRc and set value = x.AutoLoadVimRc <- value member x.AutoLoadSessionData with get() = x.AutoLoadSessionData and set value = x.AutoLoadSessionData <- value member x.FocusedBuffer = x.FocusedBuffer member x.VariableMap = x.VariableMap member x.VimBuffers = x.VimBuffers member x.VimData = _vimData member x.VimHost = _vimHost member x.VimRcState = _vimRcState member x.MacroRecorder = _recorder :> IMacroRecorder member x.MarkMap = _markMap member x.KeyMap = _keyMap member x.DigraphMap = _digraphMap member x.SearchService = _search member x.IsDisabled with get() = x.IsDisabled and set value = x.IsDisabled <- value member x.InBulkOperation = _bulkOperations.InBulkOperation member x.RegisterMap = _registerMap member x.GlobalSettings = _globalSettings member x.CloseAllVimBuffers() = x.CloseAllVimBuffers() member x.CreateVimBuffer textView = x.CreateVimBuffer textView (Some (x.GetWindowSettingsForNewBuffer())) member x.CreateVimTextBuffer textBuffer = x.CreateVimTextBuffer textBuffer (Some (x.GetLocalSettingsForNewTextBuffer())) member x.GetVimInterpreter vimBuffer = x.GetVimInterpreter vimBuffer member x.GetOrCreateVimBuffer textView = x.GetOrCreateVimBuffer textView member x.GetOrCreateVimTextBuffer textBuffer = x.GetOrCreateVimTextBuffer textBuffer member x.LoadVimRc() = x.LoadVimRc() member x.LoadSessionData() = x.LoadSessionData() member x.RemoveVimBuffer textView = x.RemoveVimBuffer textView member x.SaveSessionData() = x.SaveSessionData() member x.ShouldCreateVimBuffer textView = x.ShouldCreateVimBuffer textView member x.TryGetOrCreateVimBufferForHost(textView, vimBuffer) = x.TryGetOrCreateVimBufferForHost(textView, &vimBuffer) member x.TryGetVimBuffer(textView, vimBuffer) = x.TryGetVimBuffer(textView, &vimBuffer) member x.TryGetVimTextBuffer(textBuffer, vimBuffer) = x.TryGetVimTextBuffer(textBuffer, &vimBuffer) member x.TryGetRecentBuffer n = x.TryGetRecentBuffer n diff --git a/Src/VimCore/VimCore.fsproj b/Src/VimCore/VimCore.fsproj index 93cd3cb..710bfaf 100644 --- a/Src/VimCore/VimCore.fsproj +++ b/Src/VimCore/VimCore.fsproj @@ -1,165 +1,164 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Vim.Core</RootNamespace> <AssemblyName>Vim.Core</AssemblyName> <TargetFramework>net45</TargetFramework> <OtherFlags>--standalone</OtherFlags> <NoWarn>2011</NoWarn> <DisableImplicitFSharpCoreReference>true</DisableImplicitFSharpCoreReference> </PropertyGroup> <ItemGroup> <None Include="README.md" /> <Compile Include="Resources.fs" /> <Compile Include="Constants.fs" /> <Compile Include="FSharpUtil.fs" /> <Compile Include="VimTrace.fs" /> <Compile Include="StringUtil.fs" /> <Compile Include="Util.fs" /> <Compile Include="VimKey.fs" /> <Compile Include="KeyInput.fsi" /> <Compile Include="KeyInput.fs" /> <Compile Include="Unicode.fsi" /> <Compile Include="Unicode.fs" /> <Compile Include="CoreTypes.fs" /> <Compile Include="EditorUtil.fs" /> <Compile Include="Register.fs" /> <Compile Include="VimCharSet.fsi" /> <Compile Include="VimCharSet.fs" /> <Compile Include="VimSettingsInterface.fs" /> - <Compile Include="LineNumbersMarginOptions.fs" /> <Compile Include="Interpreter_Expression.fs" /> <Compile Include="TaggingInterfaces.fs" /> <Compile Include="WordUtil.fsi" /> <Compile Include="WordUtil.fs" /> <Compile Include="CoreInterfaces.fs" /> <Compile Include="CoreInternalInterfaces.fs" /> <Compile Include="CountCapture.fs" /> <Compile Include="VimRegexOptions.fs" /> <Compile Include="VimRegex.fsi" /> <Compile Include="VimRegex.fs" /> <Compile Include="MefInterfaces.fs" /> <Compile Include="KeyNotationUtil.fsi" /> <Compile Include="KeyNotationUtil.fs" /> <Compile Include="DigraphUtil.fs" /> <Compile Include="MotionCapture.fs" /> <Compile Include="RegexUtil.fs" /> <Compile Include="HistoryUtil.fsi" /> <Compile Include="HistoryUtil.fs" /> <Compile Include="PatternUtil.fs" /> <Compile Include="CommonOperations.fsi" /> <Compile Include="CommonOperations.fs" /> <Compile Include="Interpreter_Tokens.fs" /> <Compile Include="Interpreter_Tokenizer.fsi" /> <Compile Include="Interpreter_Tokenizer.fs" /> <Compile Include="Interpreter_Parser.fsi" /> <Compile Include="Interpreter_Parser.fs" /> <Compile Include="Interpreter_Interpreter.fsi" /> <Compile Include="Interpreter_Interpreter.fs" /> <Compile Include="CommandFactory.fsi" /> <Compile Include="CommandFactory.fs" /> <Compile Include="Modes_Command_CommandMode.fsi" /> <Compile Include="Modes_Command_CommandMode.fs" /> <Compile Include="Modes_Normal_NormalMode.fsi" /> <Compile Include="Modes_Normal_NormalMode.fs" /> <Compile Include="Modes_Insert_Components.fs" /> <Compile Include="Modes_Insert_InsertMode.fsi" /> <Compile Include="Modes_Insert_InsertMode.fs" /> <Compile Include="Modes_Visual_ISelectionTracker.fs" /> <Compile Include="Modes_Visual_SelectionTracker.fs" /> <Compile Include="Modes_Visual_VisualMode.fsi" /> <Compile Include="Modes_Visual_VisualMode.fs" /> <Compile Include="Modes_Visual_SelectMode.fsi" /> <Compile Include="Modes_Visual_SelectMode.fs" /> <Compile Include="Modes_SubstituteConfirm_SubstituteConfirmMode.fsi" /> <Compile Include="Modes_SubstituteConfirm_SubstituteConfirmMode.fs" /> <Compile Include="IncrementalSearch.fsi" /> <Compile Include="IncrementalSearch.fs" /> <Compile Include="CommandUtil.fsi" /> <Compile Include="CommandUtil.fs" /> <Compile Include="InsertUtil.fsi" /> <Compile Include="InsertUtil.fs" /> <Compile Include="TaggerUtil.fsi" /> <Compile Include="TaggerUtil.fs" /> <Compile Include="Tagger.fsi" /> <Compile Include="Tagger.fs" /> <Compile Include="CaretChangeTracker.fsi" /> <Compile Include="CaretChangeTracker.fs" /> <Compile Include="SelectionChangeTracker.fsi" /> <Compile Include="SelectionChangeTracker.fs" /> <Compile Include="FoldManager.fsi" /> <Compile Include="FoldManager.fs" /> <Compile Include="ModeLineInterpreter.fsi" /> <Compile Include="ModeLineInterpreter.fs" /> <Compile Include="VimTextBuffer.fsi" /> <Compile Include="VimTextBuffer.fs" /> <Compile Include="VimBuffer.fsi" /> <Compile Include="VimBuffer.fs" /> <Compile Include="TextObjectUtil.fsi" /> <Compile Include="TextObjectUtil.fs" /> <Compile Include="MotionUtil.fsi" /> <Compile Include="MotionUtil.fs" /> <Compile Include="SearchService.fsi" /> <Compile Include="SearchService.fs" /> <Compile Include="RegisterMap.fsi" /> <Compile Include="RegisterMap.fs" /> <Compile Include="ExternalEdit.fs" /> <Compile Include="DisabledMode.fs" /> <Compile Include="MarkMap.fsi" /> <Compile Include="MarkMap.fs" /> <Compile Include="MacroRecorder.fsi" /> <Compile Include="MacroRecorder.fs" /> <Compile Include="KeyMap.fsi" /> <Compile Include="KeyMap.fs" /> <Compile Include="DigraphMap.fsi" /> <Compile Include="DigraphMap.fs" /> <Compile Include="JumpList.fs" /> <Compile Include="VimSettings.fsi" /> <Compile Include="VimSettings.fs" /> <Compile Include="FileSystem.fs" /> <Compile Include="UndoRedoOperations.fsi" /> <Compile Include="UndoRedoOperations.fs" /> <Compile Include="CommandRunner.fsi" /> <Compile Include="CommandRunner.fs" /> <Compile Include="AutoCommandRunner.fsi" /> <Compile Include="AutoCommandRunner.fs" /> <Compile Include="Vim.fs" /> <Compile Include="StatusUtil.fsi" /> <Compile Include="StatusUtil.fs" /> <Compile Include="LineChangeTracker.fsi" /> <Compile Include="LineChangeTracker.fs" /> <Compile Include="MefComponents.fsi" /> <Compile Include="MefComponents.fs" /> <Compile Include="FSharpExtensions.fs" /> <Compile Include="AssemblyInfo.fs" /> </ItemGroup> <ItemGroup> <!-- Using element form vs. attributes to work around NuGet restore bug https://github.com/NuGet/Home/issues/6367 https://github.com/dotnet/project-system/issues/3493 --> <PackageReference Include="FSharp.Core"> <Version>4.2.3</Version> <PrivateAssets>all</PrivateAssets> </PackageReference> <!-- Excluding thes package to avoid the auto-include that is happening via F# targets and hittnig a restore issue in 15.7 https://github.com/NuGet/Home/issues/6936 --> <PackageReference Include="System.ValueTuple"> <Version>4.3.1</Version> <ExcludeAssets>all</ExcludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <Reference Include="Microsoft.VisualStudio.CoreUtility, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="Microsoft.VisualStudio.Text.Data, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="Microsoft.VisualStudio.Text.Logic, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="Microsoft.VisualStudio.Text.UI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="mscorlib" /> <Reference Include="System" /> <Reference Include="System.ComponentModel.Composition" /> <Reference Include="System.Core" /> <Reference Include="System.Numerics" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Xml" /> </ItemGroup> </Project> diff --git a/Src/VimCore/VimSettings.fs b/Src/VimCore/VimSettings.fs index 02233cf..d6c47dd 100644 --- a/Src/VimCore/VimSettings.fs +++ b/Src/VimCore/VimSettings.fs @@ -1,915 +1,962 @@ #light namespace Vim open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Editor open Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods open System.ComponentModel.Composition open System.Collections.Generic open System.Text open Vim.GlobalSettingNames open Vim.LocalSettingNames open Vim.WindowSettingNames open StringBuilderExtensions open CollectionExtensions // TODO: We need to add verification for setting options which can contain // a finite list of values. For example // - backspace, virtualedit: Setting them to an invalid value should // produce an error // - iskeyword: this can't contain a space type SettingValueParseFunc = string -> SettingValue option type internal SettingsMap ( _rawData: Setting seq ) as this = let _settingChangedEvent = StandardEvent<SettingEventArgs>() /// Map from full setting name to the actual Setting let mutable _settingMap = Dictionary<string, Setting>() /// Map from the abbreviated setting name to the full setting name let mutable _shortToFullNameMap = Dictionary<string, string>() /// Custom parsing function for a given setting name let mutable _customParseMap = Dictionary<string, SettingValueParseFunc>() do _rawData |> Seq.iter (fun setting -> this.AddSetting setting) member x.Settings = _settingMap.Values |> List.ofSeq member x.OwnsSetting settingName = x.GetSetting settingName |> Option.isSome member x.SettingChanged = _settingChangedEvent.Publish member x.AddSetting (setting: Setting) = _settingMap.Add(setting.Name, setting) _shortToFullNameMap.Add(setting.Abbreviation, setting.Name) /// Replace a Setting with a new value member x.ReplaceSetting setting = Contract.Assert (_settingMap.ContainsKey setting.Name) _settingMap.[setting.Name] <- setting let args = SettingEventArgs(setting, true) _settingChangedEvent.Trigger x args member x.AddSettingValueParseFunc settingNameOrAbbrev settingValueParseFunc = let name = x.GetFullName settingNameOrAbbrev _customParseMap.Add(name, settingValueParseFunc) member x.GetFullName settingNameOrAbbrev = match _shortToFullNameMap.TryGetValueEx settingNameOrAbbrev with | Some fullName -> fullName | None -> settingNameOrAbbrev member x.TrySetValue settingNameOrAbbrev (value: SettingValue) = let name = x.GetFullName settingNameOrAbbrev match _settingMap.TryGetValueEx name with | None -> false | Some setting -> let isValueChanged = value <> setting.Value match setting.LiveSettingValue.UpdateValue value with | Some value -> let setting = { setting with LiveSettingValue = value } _settingMap.[name] <- setting _settingChangedEvent.Trigger x (SettingEventArgs(setting, isValueChanged)) true | None -> false member x.TrySetValueFromString settingNameOrAbbrev strValue = match x.GetSetting settingNameOrAbbrev with | None -> false | Some setting -> match x.ConvertStringToValue setting strValue with | None -> false | Some value -> x.TrySetValue setting.Name value member x.GetSetting settingNameOrAbbrev: Setting option = let name = x.GetFullName settingNameOrAbbrev _settingMap.TryGetValueEx name /// Get a boolean setting value. Will throw if the setting name does not exist member x.GetBoolValue settingNameOrAbbrev = let setting = x.GetSetting settingNameOrAbbrev |> Option.get match setting.Value with | SettingValue.Toggle b -> b | SettingValue.Number _ -> failwith "invalid" | SettingValue.String _ -> failwith "invalid" /// Get a string setting value. Will throw if the setting name does not exist member x.GetStringValue settingNameOrAbbrev = let setting = x.GetSetting settingNameOrAbbrev |> Option.get match setting.Value with | SettingValue.String s -> s | SettingValue.Number _ -> failwith "invalid" | SettingValue.Toggle _ -> failwith "invalid" /// Get a number setting value. Will throw if the setting name does not exist member x.GetNumberValue settingNameOrAbbrev = let setting = x.GetSetting settingNameOrAbbrev |> Option.get match setting.Value with | SettingValue.Number n -> n | SettingValue.String _ -> failwith "invalid" | SettingValue.Toggle _ -> failwith "invalid" member x.ConvertStringToValue (setting: Setting) (str: string) = match _customParseMap.TryGetValueEx setting.Name with | None -> x.ConvertStringToValueCore str setting.Kind | Some func -> match func str with | Some settingValue -> Some settingValue | None -> x.ConvertStringToValueCore str setting.Kind member x.ConvertStringToValueCore str kind = let convertToNumber() = let ret,value = System.Int32.TryParse str if ret then Some (SettingValue.Number value) else None let convertToBoolean() = let ret,value = System.Boolean.TryParse str if ret then Some (SettingValue.Toggle value) else None match kind with | SettingKind.Number -> convertToNumber() | SettingKind.Toggle -> convertToBoolean() | SettingKind.String -> Some (SettingValue.String str) type internal GlobalSettings() = + let mutable _vimRcLocalSettings: IVimLocalSettings option = None + let mutable _vimRcWindowSettings: IVimWindowSettings option = None + /// Custom parsing for the old 'vi' style values of 'backspace'. For normal values default /// to the standard parsing behavior static let ParseBackspaceValue str = match str with | "0" -> SettingValue.String "" |> Some | "1" -> SettingValue.String "indent,eol" |> Some | "2" -> SettingValue.String "indent,eol,start" |> Some | _ -> None static let GlobalSettingInfoList = [| (AtomicInsertName, AtomicInsertName, SettingValue.Toggle false, SettingOptions.None) (BackspaceName, "bs", SettingValue.String "", SettingOptions.None) (CaretOpacityName, CaretOpacityName, SettingValue.Number 100, SettingOptions.None) (ClipboardName, "cb", SettingValue.String "", SettingOptions.None) (CurrentDirectoryPathName, "cd", SettingValue.String ",,", SettingOptions.FileName) (DigraphName, "dg", SettingValue.Toggle false, SettingOptions.None) (GlobalDefaultName, "gd", SettingValue.Toggle false, SettingOptions.None) (HighlightSearchName, "hls", SettingValue.Toggle false, SettingOptions.None) (HistoryName, "hi", SettingValue.Number(VimConstants.DefaultHistoryLength), SettingOptions.None) (IncrementalSearchName, "is", SettingValue.Toggle false, SettingOptions.None) (IgnoreCaseName,"ic", SettingValue.Toggle false, SettingOptions.None) (ImeCommandName, "imc", SettingValue.Toggle false, SettingOptions.None) (ImeDisableName, "imd", SettingValue.Toggle false, SettingOptions.None) (ImeInsertName, "imi", SettingValue.Number 0, SettingOptions.None) (ImeSearchName, "ims", SettingValue.Number -1, SettingOptions.None) (JoinSpacesName, "js", SettingValue.Toggle true, SettingOptions.None) (KeyModelName, "km", SettingValue.String "", SettingOptions.None) (LastStatusName, "ls", SettingValue.Number 0, SettingOptions.None) (MagicName, MagicName, SettingValue.Toggle true, SettingOptions.None) (MaxMapDepth, "mmd", SettingValue.Number 1000, SettingOptions.None) (ModeLineName, "ml", SettingValue.Toggle true, SettingOptions.None) (ModeLinesName, "mls", SettingValue.Number 5, SettingOptions.None) (MouseModelName, "mousem", SettingValue.String "popup", SettingOptions.None) (PathName,"pa", SettingValue.String ".,,", SettingOptions.FileName) (ParagraphsName, "para", SettingValue.String "IPLPPPQPP TPHPLIPpLpItpplpipbp", SettingOptions.None) (SectionsName, "sect", SettingValue.String "SHNHH HUnhsh", SettingOptions.None) (SelectionName, "sel", SettingValue.String "inclusive", SettingOptions.None) (SelectModeName, "slm", SettingValue.String "", SettingOptions.None) (ScrollOffsetName, "so", SettingValue.Number 0, SettingOptions.None) (ShellName, "sh", "ComSpec" |> SystemUtil.GetEnvironmentVariable |> SettingValue.String, SettingOptions.FileName) (ShellFlagName, "shcf", SettingValue.String "/c", SettingOptions.None) (ShowCommandName, "sc", SettingValue.Toggle true, SettingOptions.None) (SmartCaseName, "scs", SettingValue.Toggle false, SettingOptions.None) (StartOfLineName, "sol", SettingValue.Toggle true, SettingOptions.None) (StatusLineName, "stl", SettingValue.String "", SettingOptions.None) (TildeOpName, "top", SettingValue.Toggle false, SettingOptions.None) (TimeoutName, "to", SettingValue.Toggle true, SettingOptions.None) (TimeoutExName, TimeoutExName, SettingValue.Toggle false, SettingOptions.None) (TimeoutLengthName, "tm", SettingValue.Number 1000, SettingOptions.None) (TimeoutLengthExName, "ttm", SettingValue.Number -1, SettingOptions.None) (VimRcName, VimRcName, SettingValue.String(StringUtil.Empty), SettingOptions.FileName) (VimRcPathsName, VimRcPathsName, SettingValue.String(StringUtil.Empty), SettingOptions.FileName) (VirtualEditName, "ve", SettingValue.String(StringUtil.Empty), SettingOptions.None) (VisualBellName, "vb", SettingValue.Toggle false, SettingOptions.None) (WhichWrapName, "ww", SettingValue.String "b,s", SettingOptions.None) (WrapScanName, "ws", SettingValue.Toggle true, SettingOptions.None) |] static let GlobalSettingList = GlobalSettingInfoList |> Seq.map (fun (name, abbrev, defaultValue, options) -> { Name = name; Abbreviation = abbrev; LiveSettingValue = LiveSettingValue.Create defaultValue; IsGlobal = true; SettingOptions = options }) let _map = let settingsMap = SettingsMap(GlobalSettingList) settingsMap.AddSettingValueParseFunc BackspaceName ParseBackspaceValue settingsMap /// Mappings between the setting names and the actual options static let ClipboardOptionsMapping = [ ("unnamed", ClipboardOptions.Unnamed) ("autoselect", ClipboardOptions.AutoSelect) ("autoselectml", ClipboardOptions.AutoSelectMl) ] /// Mappings between the setting names and the actual options static let SelectModeOptionsMapping = [ ("mouse", SelectModeOptions.Mouse) ("key", SelectModeOptions.Keyboard) ("cmd", SelectModeOptions.Command) ] /// Mappings between the setting names and the actual options static let KeyModelOptionsMapping = [ ("startsel", KeyModelOptions.StartSelection) ("stopsel", KeyModelOptions.StopSelection) ] static member DisableAllCommand = KeyInputUtil.ApplyKeyModifiersToKey VimKey.F12 (VimKeyModifiers.Control ||| VimKeyModifiers.Shift) member x.AddCustomSetting name abbrevation customSettingSource = let liveSettingValue = LiveSettingValue.Custom (name, customSettingSource) let setting = { Name = name; Abbreviation = abbrevation; LiveSettingValue = liveSettingValue; IsGlobal = true; SettingOptions = SettingOptions.None } _map.AddSetting setting member x.IsCommaSubOptionPresent optionName suboptionName = _map.GetStringValue optionName |> StringUtil.Split ',' |> Seq.exists (fun x -> StringUtil.IsEqual suboptionName x) /// Convert a comma separated option into a set of type safe options member x.GetCommaOptions name mappingList emptyOption combineFunc = _map.GetStringValue name |> StringUtil.Split ',' |> Seq.fold (fun (options: 'a) (current: string)-> match List.tryFind (fun (name, _) -> name = current) mappingList with | None -> options | Some (_, value) -> combineFunc options value) emptyOption /// Convert a type safe set of options into a comma separated string member x.SetCommaOptions name mappingList options testFunc = let settingValue = mappingList |> Seq.ofList |> Seq.map (fun (name, value) -> if testFunc options value then Some name else None) |> SeqUtil.filterToSome |> String.concat "," _map.TrySetValue name (SettingValue.String settingValue) |> ignore /// Parse out the 'cdpath' or 'path' option into a strongly typed collection. The format /// for the collection is described in the documentation for 'path' but applies equally /// to both options member x.GetPathOptionList text = let length = String.length text let list = List<PathOption>() let addOne text = match text with | "." -> list.Add PathOption.CurrentFile | "" -> list.Add PathOption.CurrentDirectory | _ -> list.Add (PathOption.Named text) let builder = StringBuilder() let mutable i = 0 while i < length do match text.[i] with | '\\' -> if i + 1 < length then builder.AppendChar text.[i + 1] i <- i + 2 | ',' -> // Ignore the case where the string begins with ','. This is used to // have the first entry be ',,' and have the current directory be included if i > 0 then addOne (builder.ToString()) builder.Length <- 0 i <- i + 1 | ' ' -> // Space is also a separator addOne (builder.ToString()) builder.Length <- 0 i <- i + 1 | c -> builder.AppendChar c i <- i + 1 if builder.Length > 0 then addOne (builder.ToString()) List.ofSeq list member x.SelectionKind = match _map.GetStringValue SelectionName with | "inclusive" -> SelectionKind.Inclusive | "old" -> SelectionKind.Exclusive | _ -> SelectionKind.Exclusive interface IVimGlobalSettings with // IVimSettings member x.Settings = _map.Settings member x.TrySetValue settingName value = _map.TrySetValue settingName value member x.TrySetValueFromString settingName strValue = _map.TrySetValueFromString settingName strValue member x.GetSetting settingName = _map.GetSetting settingName // IVimGlobalSettings + member x.VimRcLocalSettings + with get() = _vimRcLocalSettings + and set value = _vimRcLocalSettings <- value + member x.VimRcWindowSettings + with get() = _vimRcWindowSettings + and set value = _vimRcWindowSettings <- value + member x.AddCustomSetting name abbrevation customSettingSource = x.AddCustomSetting name abbrevation customSettingSource member x.AtomicInsert with get() = _map.GetBoolValue AtomicInsertName and set value = _map.TrySetValue AtomicInsertName (SettingValue.Toggle value) |> ignore member x.Backspace with get() = _map.GetStringValue BackspaceName and set value = _map.TrySetValueFromString BackspaceName value |> ignore member x.CaretOpacity with get() = _map.GetNumberValue CaretOpacityName and set value = _map.TrySetValue CaretOpacityName (SettingValue.Number value) |> ignore member x.Clipboard with get() = _map.GetStringValue ClipboardName and set value = _map.TrySetValue ClipboardName (SettingValue.String value) |> ignore member x.ClipboardOptions with get() = x.GetCommaOptions ClipboardName ClipboardOptionsMapping ClipboardOptions.None (fun x y -> x ||| y) and set value = x.SetCommaOptions ClipboardName ClipboardOptionsMapping value Util.IsFlagSet member x.CurrentDirectoryPath with get() = _map.GetStringValue CurrentDirectoryPathName and set value = _map.TrySetValue CurrentDirectoryPathName (SettingValue.String value) |> ignore member x.CurrentDirectoryPathList = x.GetPathOptionList (_map.GetStringValue CurrentDirectoryPathName) member x.Digraph with get() = _map.GetBoolValue DigraphName and set value = _map.TrySetValue DigraphName (SettingValue.Toggle value) |> ignore member x.GlobalDefault with get() = _map.GetBoolValue GlobalDefaultName and set value = _map.TrySetValue GlobalDefaultName (SettingValue.Toggle value) |> ignore member x.HighlightSearch with get() = _map.GetBoolValue HighlightSearchName and set value = _map.TrySetValue HighlightSearchName (SettingValue.Toggle value) |> ignore member x.History with get () = _map.GetNumberValue HistoryName and set value = _map.TrySetValue HistoryName (SettingValue.Number value) |> ignore member x.IgnoreCase with get() = _map.GetBoolValue IgnoreCaseName and set value = _map.TrySetValue IgnoreCaseName (SettingValue.Toggle value) |> ignore member x.ImeCommand with get() = _map.GetBoolValue ImeCommandName and set value = _map.TrySetValue ImeCommandName (SettingValue.Toggle value) |> ignore member x.ImeDisable with get() = _map.GetBoolValue ImeDisableName and set value = _map.TrySetValue ImeDisableName (SettingValue.Toggle value) |> ignore member x.ImeInsert with get() = _map.GetNumberValue ImeInsertName and set value = _map.TrySetValue ImeInsertName (SettingValue.Number value) |> ignore member x.ImeSearch with get() = _map.GetNumberValue ImeSearchName and set value = _map.TrySetValue ImeSearchName (SettingValue.Number value) |> ignore member x.IncrementalSearch with get() = _map.GetBoolValue IncrementalSearchName and set value = _map.TrySetValue IncrementalSearchName (SettingValue.Toggle value) |> ignore member x.IsSelectionInclusive = x.SelectionKind = SelectionKind.Inclusive member x.IsSelectionPastLine = match _map.GetStringValue SelectionName with | "exclusive" -> true | "inclusive" -> true | _ -> false member x.JoinSpaces with get() = _map.GetBoolValue JoinSpacesName and set value = _map.TrySetValue JoinSpacesName (SettingValue.Toggle value) |> ignore member x.KeyModel with get() = _map.GetStringValue KeyModelName and set value = _map.TrySetValue KeyModelName (SettingValue.String value) |> ignore member x.KeyModelOptions with get() = x.GetCommaOptions KeyModelName KeyModelOptionsMapping KeyModelOptions.None (fun x y -> x ||| y) and set value = x.SetCommaOptions KeyModelName KeyModelOptionsMapping value Util.IsFlagSet member x.LastStatus with get() = _map.GetNumberValue LastStatusName and set value = _map.TrySetValue LastStatusName (SettingValue.Number value) |> ignore member x.Magic with get() = _map.GetBoolValue MagicName and set value = _map.TrySetValue MagicName (SettingValue.Toggle value) |> ignore member x.MaxMapDepth with get() = _map.GetNumberValue MaxMapDepth and set value = _map.TrySetValue MaxMapDepth (SettingValue.Number value) |> ignore member x.ModeLine with get() = _map.GetBoolValue ModeLineName and set value = _map.TrySetValue ModeLineName (SettingValue.Toggle value) |> ignore member x.ModeLines with get() = _map.GetNumberValue ModeLinesName and set value = _map.TrySetValue ModeLinesName (SettingValue.Number value) |> ignore member x.MouseModel with get() = _map.GetStringValue MouseModelName and set value = _map.TrySetValue MouseModelName (SettingValue.String value) |> ignore member x.Paragraphs with get() = _map.GetStringValue ParagraphsName and set value = _map.TrySetValue ParagraphsName (SettingValue.String value) |> ignore member x.Path with get() = _map.GetStringValue PathName and set value = _map.TrySetValue PathName (SettingValue.String value) |> ignore member x.PathList = x.GetPathOptionList (_map.GetStringValue PathName) member x.ScrollOffset with get() = _map.GetNumberValue ScrollOffsetName and set value = _map.TrySetValue ScrollOffsetName (SettingValue.Number value) |> ignore member x.Sections with get() = _map.GetStringValue SectionsName and set value = _map.TrySetValue SectionsName (SettingValue.String value) |> ignore member x.Selection with get() = _map.GetStringValue SelectionName and set value = _map.TrySetValue SelectionName (SettingValue.String value) |> ignore member x.SelectionKind = x.SelectionKind member x.SelectMode with get() = _map.GetStringValue SelectModeName and set value = _map.TrySetValue SelectModeName (SettingValue.String value) |> ignore member x.SelectModeOptions with get() = x.GetCommaOptions SelectModeName SelectModeOptionsMapping SelectModeOptions.None (fun x y -> x ||| y) and set value = x.SetCommaOptions SelectModeName SelectModeOptionsMapping value Util.IsFlagSet member x.Shell with get() = _map.GetStringValue ShellName and set value = _map.TrySetValue ShellName (SettingValue.String value) |> ignore member x.ShellFlag with get() = _map.GetStringValue ShellFlagName and set value = _map.TrySetValue ShellFlagName (SettingValue.String value) |> ignore member x.ShowCommand with get() = _map.GetBoolValue ShowCommandName and set value = _map.TrySetValue ShowCommandName (SettingValue.Toggle value) |> ignore member x.SmartCase with get() = _map.GetBoolValue SmartCaseName and set value = _map.TrySetValue SmartCaseName (SettingValue.Toggle value) |> ignore member x.StartOfLine with get() = _map.GetBoolValue StartOfLineName and set value = _map.TrySetValue StartOfLineName (SettingValue.Toggle value) |> ignore member x.StatusLine with get() = _map.GetStringValue StatusLineName and set value = _map.TrySetValue StatusLineName (SettingValue.String value) |> ignore member x.TildeOp with get() = _map.GetBoolValue TildeOpName and set value = _map.TrySetValue TildeOpName (SettingValue.Toggle value) |> ignore member x.Timeout with get() = _map.GetBoolValue TimeoutName and set value = _map.TrySetValue TimeoutName (SettingValue.Toggle value) |> ignore member x.TimeoutEx with get() = _map.GetBoolValue TimeoutExName and set value = _map.TrySetValue TimeoutExName (SettingValue.Toggle value) |> ignore member x.TimeoutLength with get() = _map.GetNumberValue TimeoutLengthName and set value = _map.TrySetValue TimeoutLengthName (SettingValue.Number value) |> ignore member x.TimeoutLengthEx with get() = _map.GetNumberValue TimeoutLengthExName and set value = _map.TrySetValue TimeoutLengthExName (SettingValue.Number value) |> ignore member x.VimRc with get() = _map.GetStringValue VimRcName and set value = _map.TrySetValue VimRcName (SettingValue.String value) |> ignore member x.VimRcPaths with get() = _map.GetStringValue VimRcPathsName and set value = _map.TrySetValue VimRcPathsName (SettingValue.String value) |> ignore member x.VirtualEdit with get() = _map.GetStringValue VirtualEditName and set value = _map.TrySetValue VirtualEditName (SettingValue.String value) |> ignore member x.VisualBell with get() = _map.GetBoolValue VisualBellName and set value = _map.TrySetValue VisualBellName (SettingValue.Toggle value) |> ignore member x.WhichWrap with get() = _map.GetStringValue WhichWrapName and set value = _map.TrySetValue WhichWrapName (SettingValue.String value) |> ignore member x.WrapScan with get() = _map.GetBoolValue WrapScanName and set value = _map.TrySetValue WrapScanName (SettingValue.Toggle value) |> ignore member x.DisableAllCommand = GlobalSettings.DisableAllCommand member x.IsBackspaceEol = x.IsCommaSubOptionPresent BackspaceName "eol" member x.IsBackspaceIndent = x.IsCommaSubOptionPresent BackspaceName "indent" member x.IsBackspaceStart = x.IsCommaSubOptionPresent BackspaceName "start" member x.IsVirtualEditBlock = x.IsCommaSubOptionPresent VirtualEditName "block" || x.IsCommaSubOptionPresent VirtualEditName "all" member x.IsVirtualEditInsert = x.IsCommaSubOptionPresent VirtualEditName "insert" || x.IsCommaSubOptionPresent VirtualEditName "all" member x.IsVirtualEditAll = x.IsCommaSubOptionPresent VirtualEditName "all" member x.IsVirtualEditOneMore = x.IsCommaSubOptionPresent VirtualEditName "onemore" || x.IsCommaSubOptionPresent VirtualEditName "all" member x.IsWhichWrapSpaceLeft = x.IsCommaSubOptionPresent WhichWrapName "b" member x.IsWhichWrapSpaceRight = x.IsCommaSubOptionPresent WhichWrapName "s" member x.IsWhichWrapCharLeft = x.IsCommaSubOptionPresent WhichWrapName "h" member x.IsWhichWrapCharRight = x.IsCommaSubOptionPresent WhichWrapName "l" member x.IsWhichWrapArrowLeft = x.IsCommaSubOptionPresent WhichWrapName "<" member x.IsWhichWrapArrowRight = x.IsCommaSubOptionPresent WhichWrapName ">" member x.IsWhichWrapTilde = x.IsCommaSubOptionPresent WhichWrapName "~" member x.IsWhichWrapArrowLeftInsert = x.IsCommaSubOptionPresent WhichWrapName "[" member x.IsWhichWrapArrowRightInsert = x.IsCommaSubOptionPresent WhichWrapName "]" [<CLIEvent>] member x.SettingChanged = _map.SettingChanged type internal LocalSettings ( _globalSettings: IVimGlobalSettings ) = static let IsKeywordCharSetDefault = VimCharSet.TryParse("@,48-57,_,128-167,224-235") |> Option.get static let LocalSettingInfoList = [| (AutoIndentName, "ai", SettingValue.Toggle false, SettingOptions.None) (ExpandTabName, "et", SettingValue.Toggle false, SettingOptions.None) (NumberName, "nu", SettingValue.Toggle false, SettingOptions.None) (NumberFormatsName, "nf", SettingValue.String "bin,octal,hex", SettingOptions.None) (RelativeNumberName, "rnu", SettingValue.Toggle false, SettingOptions.None) (SoftTabStopName, "sts", SettingValue.Number 0, SettingOptions.None) (ShiftWidthName, "sw", SettingValue.Number 8, SettingOptions.None) (TabStopName, "ts", SettingValue.Number 8, SettingOptions.None) (ListName, "list", SettingValue.Toggle false, SettingOptions.None) (QuoteEscapeName, "qe", SettingValue.String @"\", SettingOptions.None) (EndOfLineName, "eol", SettingValue.Toggle true, SettingOptions.None) (FixEndOfLineName, "fixeol", SettingValue.Toggle false, SettingOptions.None) (TextWidthName, "tw", SettingValue.Number 0, SettingOptions.None) (CommentsName, "com", SettingValue.String ":*,://,:#,:;", SettingOptions.None) (IsKeywordName, "isk", SettingValue.String IsKeywordCharSetDefault.Text, SettingOptions.None) |] static let LocalSettingList = LocalSettingInfoList |> Seq.map (fun (name, abbrev, defaultValue, options) -> { Name = name; Abbreviation = abbrev; LiveSettingValue = LiveSettingValue.Create defaultValue; IsGlobal = false; SettingOptions = options }) let _map = SettingsMap(LocalSettingList) + member x.Defaults = + match _globalSettings.VimRcLocalSettings with + | Some localSettings -> localSettings + | None -> LocalSettings(_globalSettings) :> IVimLocalSettings + member x.Map = _map static member Copy (settings: IVimLocalSettings) = let copy = LocalSettings(settings.GlobalSettings) settings.Settings |> Seq.filter (fun s -> not s.IsValueCalculated) |> Seq.iter (fun s -> copy.Map.TrySetValue s.Name s.Value |> ignore) copy :> IVimLocalSettings member x.IsNumberFormatSupported numberFormat = // The format is supported if the name is in the comma delimited value let isSupported format = _map.GetStringValue NumberFormatsName |> StringUtil.Split ',' |> Seq.exists (fun value -> value = format) match numberFormat with | NumberFormat.Decimal -> // This is always supported independent of the option value true | NumberFormat.Binary -> isSupported "bin" | NumberFormat.Octal -> isSupported "octal" | NumberFormat.Hex -> isSupported "hex" | NumberFormat.Alpha -> isSupported "alpha" member x.TrySetValue settingName value = if _map.OwnsSetting settingName then _map.TrySetValue settingName value else _globalSettings.TrySetValue settingName value member x.TrySetValueFromString settingName strValue = if _map.OwnsSetting settingName then _map.TrySetValueFromString settingName strValue else _globalSettings.TrySetValueFromString settingName strValue member x.GetSetting settingName = if _map.OwnsSetting settingName then _map.GetSetting settingName else _globalSettings.GetSetting settingName interface IVimLocalSettings with // IVimSettings - + + member x.Defaults = x.Defaults member x.Settings = _map.Settings member x.TrySetValue settingName value = x.TrySetValue settingName value member x.TrySetValueFromString settingName strValue = x.TrySetValueFromString settingName strValue member x.GetSetting settingName = x.GetSetting settingName member x.GlobalSettings = _globalSettings member x.AutoIndent with get() = _map.GetBoolValue AutoIndentName and set value = _map.TrySetValue AutoIndentName (SettingValue.Toggle value) |> ignore member x.ExpandTab with get() = _map.GetBoolValue ExpandTabName and set value = _map.TrySetValue ExpandTabName (SettingValue.Toggle value) |> ignore member x.Number with get() = _map.GetBoolValue NumberName and set value = _map.TrySetValue NumberName (SettingValue.Toggle value) |> ignore member x.NumberFormats with get() = _map.GetStringValue NumberFormatsName and set value = _map.TrySetValue NumberFormatsName (SettingValue.String value) |> ignore member x.RelativeNumber with get() = _map.GetBoolValue RelativeNumberName and set value = _map.TrySetValue RelativeNumberName (SettingValue.Toggle value) |> ignore member x.SoftTabStop with get() = _map.GetNumberValue SoftTabStopName and set value = _map.TrySetValue SoftTabStopName (SettingValue.Number value) |> ignore member x.ShiftWidth with get() = _map.GetNumberValue ShiftWidthName and set value = _map.TrySetValue ShiftWidthName (SettingValue.Number value) |> ignore member x.TabStop with get() = _map.GetNumberValue TabStopName and set value = _map.TrySetValue TabStopName (SettingValue.Number value) |> ignore member x.List with get() = _map.GetBoolValue ListName and set value = _map.TrySetValue ListName (SettingValue.Toggle value) |> ignore member x.QuoteEscape with get() = _map.GetStringValue QuoteEscapeName and set value = _map.TrySetValue QuoteEscapeName (SettingValue.String value) |> ignore member x.EndOfLine with get() = _map.GetBoolValue EndOfLineName and set value = _map.TrySetValue EndOfLineName (SettingValue.Toggle value) |> ignore member x.FixEndOfLine with get() = _map.GetBoolValue FixEndOfLineName and set value = _map.TrySetValue FixEndOfLineName (SettingValue.Toggle value) |> ignore member x.TextWidth with get() = _map.GetNumberValue TextWidthName and set value = _map.TrySetValue TextWidthName (SettingValue.Number value) |> ignore member x.Comments with get() = _map.GetStringValue CommentsName and set value = _map.TrySetValue CommentsName (SettingValue.String value) |> ignore member x.IsKeyword with get() = _map.GetStringValue IsKeywordName and set value = _map.TrySetValue IsKeywordName (SettingValue.String value) |> ignore member x.IsKeywordCharSet with get() = match VimCharSet.TryParse (_map.GetStringValue IsKeywordName) with Some s -> s | None -> IsKeywordCharSetDefault and set value = _map.TrySetValue IsKeywordName (SettingValue.String value.Text) |> ignore member x.IsNumberFormatSupported numberFormat = x.IsNumberFormatSupported numberFormat [<CLIEvent>] member x.SettingChanged = _map.SettingChanged type internal WindowSettings ( _globalSettings: IVimGlobalSettings, _textView: ITextView option ) as this = static let WindowSettingInfoList = [| (CursorLineName, "cul", SettingValue.Toggle false, SettingOptions.None) (ScrollName, "scr", SettingValue.Number 25, SettingOptions.None) (WrapName, WrapName, SettingValue.Toggle false, SettingOptions.None) |] static let WindowSettingList = WindowSettingInfoList |> Seq.map (fun (name, abbrev, defaultValue, options) -> { Name = name; Abbreviation = abbrev; LiveSettingValue = LiveSettingValue.Create defaultValue; IsGlobal = false; SettingOptions = options }) let _map = SettingsMap(WindowSettingList) do let setting = _map.GetSetting ScrollName |> Option.get let liveSettingValue = LiveSettingValue.CalculatedNumber (None, this.CalculateScroll) let setting = { setting with LiveSettingValue = liveSettingValue } _map.ReplaceSetting setting new (settings) = WindowSettings(settings, None) new (settings, textView: ITextView) = WindowSettings(settings, Some textView) + member x.Defaults = + match _globalSettings.VimRcWindowSettings with + | Some windowSettings -> windowSettings + | None -> WindowSettings(_globalSettings, _textView) :> IVimWindowSettings + member x.Map = _map /// Calculate the scroll value as specified in the Vim documentation. Should be half the number of /// visible lines member x.CalculateScroll() = let defaultValue = 10 match _textView with | None -> defaultValue | Some textView -> int (textView.ViewportHeight / textView.LineHeight / 2.0 + 0.5) static member Copy (settings: IVimWindowSettings) = let copy = WindowSettings(settings.GlobalSettings) settings.Settings |> Seq.filter (fun s -> not s.IsValueCalculated) |> Seq.iter (fun s -> copy.Map.TrySetValue s.Name s.Value |> ignore) copy :> IVimWindowSettings interface IVimWindowSettings with + member x.Defaults = x.Defaults member x.Settings = _map.Settings member x.TrySetValue settingName value = if _map.OwnsSetting settingName then _map.TrySetValue settingName value else _globalSettings.TrySetValue settingName value member x.TrySetValueFromString settingName strValue = if _map.OwnsSetting settingName then _map.TrySetValueFromString settingName strValue else _globalSettings.TrySetValueFromString settingName strValue member x.GetSetting settingName = if _map.OwnsSetting settingName then _map.GetSetting settingName else _globalSettings.GetSetting settingName member x.GlobalSettings = _globalSettings member x.CursorLine with get() = _map.GetBoolValue CursorLineName and set value = _map.TrySetValue CursorLineName (SettingValue.Toggle value) |> ignore member x.Scroll with get() = _map.GetNumberValue ScrollName and set value = _map.TrySetValue ScrollName (SettingValue.Number value) |> ignore member x.Wrap with get() = _map.GetBoolValue WrapName and set value = _map.TrySetValue WrapName (SettingValue.Toggle value) |> ignore [<CLIEvent>] member x.SettingChanged = _map.SettingChanged /// Certain changes need to be synchronized between the editor, local and global /// settings. This MEF component takes care of that synchronization [<Export(typeof<IEditorToSettingsSynchronizer>)>] type internal EditorToSettingSynchronizer [<ImportingConstructor>] () = let _syncronizingSet = System.Collections.Generic.HashSet<IVimLocalSettings>() let _settingList = System.Collections.Generic.List<SettingSyncData>() let _key = obj() do _settingList.Add( { EditorOptionKey = DefaultOptions.TabSizeOptionId.Name GetEditorValue = SettingSyncData.GetNumberValueFunc DefaultOptions.TabSizeOptionId - VimSettingName = LocalSettingNames.TabStopName - GetVimSettingValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.TabStopName true + VimSettingNames = [LocalSettingNames.TabStopName] + GetVimValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.TabStopName true + SetVimValue = SettingSyncData.SetVimValueFunc LocalSettingNames.TabStopName true IsLocal = true }) _settingList.Add( { EditorOptionKey = DefaultOptions.IndentSizeOptionId.Name GetEditorValue = SettingSyncData.GetNumberValueFunc DefaultOptions.IndentSizeOptionId - VimSettingName = LocalSettingNames.ShiftWidthName - GetVimSettingValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ShiftWidthName true + VimSettingNames = [LocalSettingNames.ShiftWidthName] + GetVimValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ShiftWidthName true + SetVimValue = SettingSyncData.SetVimValueFunc LocalSettingNames.ShiftWidthName true IsLocal = true }) _settingList.Add( { EditorOptionKey = DefaultOptions.ConvertTabsToSpacesOptionId.Name GetEditorValue = SettingSyncData.GetBoolValueFunc DefaultOptions.ConvertTabsToSpacesOptionId - VimSettingName = LocalSettingNames.ExpandTabName - GetVimSettingValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ExpandTabName true + VimSettingNames = [LocalSettingNames.ExpandTabName] + GetVimValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ExpandTabName true + SetVimValue = SettingSyncData.SetVimValueFunc LocalSettingNames.ExpandTabName true IsLocal = true }) _settingList.Add( { EditorOptionKey = DefaultTextViewHostOptions.LineNumberMarginId.Name GetEditorValue = SettingSyncData.GetBoolValueFunc DefaultTextViewHostOptions.LineNumberMarginId - VimSettingName = LocalSettingNames.NumberName - GetVimSettingValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.NumberName true - IsLocal = true - }) - - _settingList.Add( - { - EditorOptionKey = LineNumbersMarginOptions.LineNumbersMarginOptionName - GetEditorValue = SettingSyncData.GetBoolValueFunc LineNumbersMarginOptions.LineNumbersMarginOptionId - VimSettingName = LocalSettingNames.RelativeNumberName - GetVimSettingValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.RelativeNumberName true + VimSettingNames = [LocalSettingNames.NumberName; LocalSettingNames.RelativeNumberName] + GetVimValue = (fun vimBuffer -> + let localSettings = vimBuffer.LocalSettings + (localSettings.Number || localSettings.RelativeNumber) |> box) + SetVimValue = (fun vimBuffer value -> + let localSettings = vimBuffer.LocalSettings + let enableNumber, enableRelativeNumber = + match value with + | SettingValue.Toggle true -> + // The editor line number option is enabled. If + // either or both of the user defaults for 'number' + // and 'relativenumber' are set, then use those + // defaults. Otherwise enable only 'number'. + let localSettingDefaults = localSettings.Defaults + let defaultNumber = localSettingDefaults.Number + let defaultRelativeNumber = localSettingDefaults.RelativeNumber + if defaultNumber || defaultRelativeNumber then + defaultNumber, defaultRelativeNumber + else + true, false + | _ -> + false, false + let setSettingValue name enableSetting = + SettingValue.Toggle enableSetting + |> localSettings.TrySetValue name + |> ignore + setSettingValue LocalSettingNames.NumberName enableNumber + setSettingValue LocalSettingNames.RelativeNumberName enableRelativeNumber) IsLocal = true }) _settingList.Add( { EditorOptionKey = DefaultTextViewOptions.WordWrapStyleId.Name GetEditorValue = (fun editorOptions -> match EditorOptionsUtil.GetOptionValue editorOptions DefaultTextViewOptions.WordWrapStyleId with | None -> None | Some s -> Util.IsFlagSet s WordWrapStyles.WordWrap |> SettingValue.Toggle |> Option.Some) - VimSettingName = WindowSettingNames.WrapName - GetVimSettingValue = (fun vimBuffer -> + VimSettingNames = [WindowSettingNames.WrapName] + GetVimValue = (fun vimBuffer -> let windowSettings = vimBuffer.WindowSettings // Wrap is a difficult option because vim has wrap as on / off while the core editor has // 3 different kinds of wrapping. If we default to only one of them then we will constantly // be undoing user settings. Hence we consider anything but off to be on and hence won't change it let wordWrap = if windowSettings.Wrap then let vimHost = vimBuffer.Vim.VimHost vimHost.GetWordWrapStyle vimBuffer.TextView else WordWrapStyles.None box wordWrap) + SetVimValue = SettingSyncData.SetVimValueFunc WindowSettingNames.WrapName false IsLocal = false }) _settingList.Add( { EditorOptionKey = DefaultTextViewOptions.UseVisibleWhitespaceId.Name GetEditorValue = SettingSyncData.GetBoolValueFunc DefaultTextViewOptions.UseVisibleWhitespaceId - VimSettingName = LocalSettingNames.ListName - GetVimSettingValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ListName true + VimSettingNames = [LocalSettingNames.ListName] + GetVimValue = SettingSyncData.GetSettingValueFunc LocalSettingNames.ListName true + SetVimValue = SettingSyncData.SetVimValueFunc LocalSettingNames.ListName true IsLocal = true }) member x.StartSynchronizing (vimBuffer: IVimBuffer) settingSyncSource = let properties = vimBuffer.TextView.Properties if not (properties.ContainsProperty _key) then properties.AddProperty(_key, _key) x.SetupSynchronization vimBuffer + // Vim doesn't consider folding an undo operation, and neither does VsVim (issue #2184). + vimBuffer.TextView.Options.SetOptionValue(DefaultTextViewOptions.OutliningUndoOptionId, false) + match settingSyncSource with | SettingSyncSource.Editor -> x.CopyEditorToVimSettings vimBuffer | SettingSyncSource.Vim -> x.CopyVimToEditorSettings vimBuffer // Any applicable modeline takes precedence over both the editor // and the default settings. Apply modeline settings now that we // have synchronized the local settings between the editor and the // defaults. match vimBuffer.VimTextBuffer.CheckModeLine vimBuffer.WindowSettings with | Some modeLine, Some badOption -> Resources.Common_InvalidModeLineSetting badOption modeLine |> vimBuffer.VimBufferData.StatusUtil.OnError | _ -> () member x.SetupSynchronization (vimBuffer: IVimBuffer) = let editorOptions = vimBuffer.TextView.Options if editorOptions <> null then let properties = vimBuffer.TextView.Properties let bag = DisposableBag() // Raised when a local setting is changed. We need to inspect this setting and // determine if it's an interesting setting and if so synchronize it with the // editor options // // Cast up to IVimSettings to avoid the F# bug of accessing a CLIEvent from // a derived interface let localSettings = vimBuffer.LocalSettings (localSettings :> IVimSettings).SettingChanged |> Observable.filter (fun args -> x.IsTrackedLocalSetting args.Setting) |> Observable.subscribe (fun _ -> x.CopyVimToEditorSettings vimBuffer) |> bag.Add // Cast up to IVimSettings to avoid the F# bug of accessing a CLIEvent from // a derived interface let windowSettings = vimBuffer.WindowSettings (windowSettings :> IVimSettings).SettingChanged |> Observable.filter (fun args -> x.IsTrackedWindowSetting args.Setting) |> Observable.subscribe (fun _ -> x.CopyVimToEditorSettings vimBuffer) |> bag.Add /// Raised when an editor option is changed. If it's one of the values we care about /// then we need to sync to the local settings editorOptions.OptionChanged |> Observable.filter (fun e -> x.IsTrackedEditorSetting e.OptionId) |> Observable.subscribe (fun _ -> x.CopyEditorToVimSettings vimBuffer) |> bag.Add // Finally we need to clean up our listeners when the buffer is closed. At // that point synchronization is no longer needed vimBuffer.Closed |> Observable.add (fun _ -> properties.RemoveProperty _key |> ignore bag.DisposeAll()) /// Is this a local setting of note member x.IsTrackedLocalSetting (setting: Setting) = - _settingList |> Seq.exists (fun x -> x.IsLocal && x.VimSettingName = setting.Name) + _settingList |> Seq.exists (fun x -> x.IsLocal && List.contains setting.Name x.VimSettingNames) /// Is this a window setting of note member x.IsTrackedWindowSetting (setting: Setting) = - _settingList |> Seq.exists (fun x -> not x.IsLocal && x.VimSettingName = setting.Name) + _settingList |> Seq.exists (fun x -> not x.IsLocal && List.contains setting.Name x.VimSettingNames) /// Is this an editor setting of note member x.IsTrackedEditorSetting optionId = _settingList |> Seq.exists (fun x -> x.EditorOptionKey = optionId) /// Synchronize the settings if needed. Prevent recursive sync's here member x.TrySync (vimBuffer: IVimBuffer) syncFunc = let editorOptions = vimBuffer.TextView.Options if editorOptions <> null then let localSettings = vimBuffer.LocalSettings if _syncronizingSet.Add(localSettings) then try syncFunc vimBuffer editorOptions finally _syncronizingSet.Remove(localSettings) |> ignore /// Synchronize the settings from the editor to the local settings. Do not /// call this directly but instead call through SynchronizeSettings member x.CopyVimToEditorSettings vimBuffer = x.TrySync vimBuffer (fun vimBuffer editorOptions -> for data in _settingList do - let value = data.GetVimSettingValue vimBuffer + let settings = data.GetSettings vimBuffer + let value = data.GetVimValue vimBuffer if value <> null then editorOptions.SetOptionValue(data.EditorOptionKey, value)) /// Synchronize the settings from the local settings to the editor. Do not /// call this directly but instead call through SynchronizeSettings member x.CopyEditorToVimSettings (vimBuffer: IVimBuffer) = x.TrySync vimBuffer (fun vimBuffer editorOptions -> for data in _settingList do match data.GetEditorValue editorOptions with | None -> () | Some value -> - let settings = data.GetSettings vimBuffer - settings.TrySetValue data.VimSettingName value |> ignore) + data.SetVimValue vimBuffer value) interface IEditorToSettingsSynchronizer with member x.StartSynchronizing vimBuffer settingSyncSource = x.StartSynchronizing vimBuffer settingSyncSource member x.SyncSetting data = _settingList.Add data diff --git a/Src/VimCore/VimSettingsInterface.fs b/Src/VimCore/VimSettingsInterface.fs index 2e8716d..6392c4f 100644 --- a/Src/VimCore/VimSettingsInterface.fs +++ b/Src/VimCore/VimSettingsInterface.fs @@ -1,625 +1,635 @@ namespace Vim open Microsoft.VisualStudio.Text open Microsoft.VisualStudio.Text.Editor open Microsoft.VisualStudio.Text.Operations open Microsoft.VisualStudio.Text.Outlining open Microsoft.VisualStudio.Utilities open System.Diagnostics open System.Runtime.CompilerServices open System.Collections.Generic module GlobalSettingNames = let AtomicInsertName = "vsvimatomicinsert" let BackspaceName = "backspace" let CaretOpacityName = "vsvimcaret" let CurrentDirectoryPathName = "cdpath" let ClipboardName = "clipboard" let DigraphName = "digraph" let GlobalDefaultName = "gdefault" let HighlightSearchName = "hlsearch" let HistoryName = "history" let IgnoreCaseName = "ignorecase" let ImeCommandName = "imcmdline" let ImeDisableName = "imdisable" let ImeInsertName = "iminsert" let ImeSearchName= "imsearch" let IncrementalSearchName = "incsearch" let JoinSpacesName = "joinspaces" let KeyModelName = "keymodel" let LastStatusName = "laststatus" let MagicName = "magic" let MaxMapDepth = "maxmapdepth" let ModeLineName = "modeline" let ModeLinesName = "modelines" let MouseModelName = "mousemodel" let ParagraphsName = "paragraphs" let PathName = "path" let ScrollOffsetName = "scrolloff" let SectionsName = "sections" let SelectionName = "selection" let SelectModeName = "selectmode" let ShellName = "shell" let ShellFlagName = "shellcmdflag" let ShowCommandName = "showcmd" let SmartCaseName = "smartcase" let StartOfLineName = "startofline" let StatusLineName = "statusline" let TildeOpName = "tildeop" let TimeoutExName = "ttimeout" let TimeoutName = "timeout" let TimeoutLengthName = "timeoutlen" let TimeoutLengthExName = "ttimeoutlen" let VisualBellName = "visualbell" let VirtualEditName = "virtualedit" let VimRcName = "vimrc" let VimRcPathsName = "vimrcpaths" let WhichWrapName = "whichwrap" let WrapScanName = "wrapscan" module LocalSettingNames = let AutoIndentName = "autoindent" let ExpandTabName = "expandtab" let NumberName = "number" let NumberFormatsName = "nrformats" let RelativeNumberName = "relativenumber" let SoftTabStopName = "softtabstop" let ShiftWidthName = "shiftwidth" let TabStopName = "tabstop" let ListName = "list" let QuoteEscapeName = "quoteescape" let EndOfLineName = "endofline" let FixEndOfLineName = "fixendofline" let TextWidthName = "textwidth" let CommentsName = "comments" let IsKeywordName = "iskeyword" module WindowSettingNames = let CursorLineName = "cursorline" let ScrollName = "scroll" let WrapName = "wrap" /// Qualifiers that options can have [<RequireQualifiedAccess>] type SettingOptions = | None = 0 /// A string setting that is used as a filename undergoes limited /// backslash escaping and expands environment variables | FileName = 0x1 /// Types of number formats supported by CTRL-A CTRL-A [<RequireQualifiedAccess>] [<NoComparison>] type NumberFormat = | Alpha | Decimal | Hex | Octal | Binary /// The options which can be set in the 'clipboard' setting [<RequireQualifiedAccess>] type ClipboardOptions = | None = 0 | Unnamed = 0x1 | AutoSelect = 0x2 | AutoSelectMl = 0x4 /// The options which can be set in the 'selectmode' setting [<RequireQualifiedAccess>] type SelectModeOptions = | None = 0 | Mouse = 0x1 | Keyboard = 0x2 | Command = 0x4 /// The options which can be set in the 'keymodel' setting [<RequireQualifiedAccess>] type KeyModelOptions = | None = 0 | StartSelection = 0x1 | StopSelection = 0x2 /// The type of path values which can appear for 'cdpath' or 'path' [<RequireQualifiedAccess>] [<NoComparison>] [<StructuralEquality>] type PathOption = /// An actual named path | Named of Named: string /// Use the current directory | CurrentDirectory /// Use the directory of the current file | CurrentFile [<RequireQualifiedAccess>] [<NoComparison>] type SelectionKind = | Inclusive | Exclusive [<RequireQualifiedAccess>] [<NoComparison>] type SettingKind = | Number | String | Toggle /// A concrete value attached to a setting [<RequireQualifiedAccess>] [<StructuralEquality>] [<NoComparison>] type SettingValue = | Number of Number: int | String of String: string | Toggle of Toggle: bool member x.Kind = match x with | Number _ -> SettingKind.Number | String _ -> SettingKind.String | Toggle _ -> SettingKind.Toggle /// Allows for custom setting sources to be defined. This is used by the vim host to /// add custom settings type IVimCustomSettingSource = abstract GetDefaultSettingValue: name: string -> SettingValue abstract GetSettingValue: name: string -> SettingValue abstract SetSettingValue: name: string -> settingValue: SettingValue -> unit /// This pairs both the current setting value and the default value into a single type safe /// value. The first value in every tuple is the current value while the second is the /// default [<RequireQualifiedAccess>] type LiveSettingValue = | Number of Value: int * DefaultValue: int | String of Value: string * DefaultValue: string | Toggle of Value: bool * DefaultValue: bool | CalculatedNumber of Value: int option * DefaultValueFunc: (unit -> int) | Custom of Value: string * DefaultValueSource: IVimCustomSettingSource /// Is this a calculated value member x.IsCalculated = match x with | CalculatedNumber _ -> true | _ -> false member x.Value = match x with | Number (value, _) -> SettingValue.Number value | String (value, _) -> SettingValue.String value | Toggle (value, _) -> SettingValue.Toggle value | CalculatedNumber (value, func) -> match value with | Some value -> SettingValue.Number value | None -> func() |> SettingValue.Number | Custom (name, customSettingSource) -> customSettingSource.GetSettingValue name member x.DefaultValue = match x with | Number (_, defaultValue) -> SettingValue.Number defaultValue | String (_, defaultValue) -> SettingValue.String defaultValue | Toggle (_, defaultValue) -> SettingValue.Toggle defaultValue | CalculatedNumber (_, func) -> func() |> SettingValue.Number | Custom (name, customSettingSource) -> customSettingSource.GetDefaultSettingValue name /// Is the value currently the default? member x.IsValueDefault = x.Value = x.DefaultValue member x.Kind = match x with | Number _ -> SettingKind.Number | String _ -> SettingKind.String | Toggle _ -> SettingKind.Toggle | CalculatedNumber _ -> SettingKind.Number | Custom (name, customSettingSource) -> (customSettingSource.GetDefaultSettingValue name).Kind member x.UpdateValue value = match x, value with | Number (_, defaultValue), SettingValue.Number value -> Number (value, defaultValue) |> Some | String (_, defaultValue), SettingValue.String value -> String (value, defaultValue) |> Some | Toggle (_, defaultValue), SettingValue.Toggle value -> Toggle (value, defaultValue) |> Some | CalculatedNumber (_, func), SettingValue.Number value -> if value = 0 then CalculatedNumber (None, func) else CalculatedNumber (Some value, func) |> Some | Custom (name, customSettingSource), value -> customSettingSource.SetSettingValue name value Some x | _ -> None static member Create value = match value with | SettingValue.Number value -> LiveSettingValue.Number (value, value) | SettingValue.String value -> LiveSettingValue.String (value, value) | SettingValue.Toggle value -> LiveSettingValue.Toggle (value, value) [<DebuggerDisplay("{Name}={Value}")>] type Setting = { Name: string Abbreviation: string LiveSettingValue: LiveSettingValue IsGlobal: bool SettingOptions: SettingOptions } with member x.Value = x.LiveSettingValue.Value member x.DefaultValue = x.LiveSettingValue.DefaultValue member x.Kind = x.LiveSettingValue.Kind /// Is the value calculated member x.IsValueCalculated = x.LiveSettingValue.IsCalculated /// Is the setting value currently set to the default value member x.IsValueDefault = x.LiveSettingValue.IsValueDefault /// Whether the setting has the FileName member x.HasFileNameOption = Util.IsFlagSet x.SettingOptions SettingOptions.FileName type SettingEventArgs(_setting: Setting, _isValueChanged: bool) = inherit System.EventArgs() /// The affected setting member x.Setting = _setting /// Determine if the value changed or not. The event is raised for sets that don't change the /// value because there is a lot of vim specific behavior that depends on this (:noh). This /// will help the handlers which want to look for actual changes member x.IsValueChanged = _isValueChanged; /// Represent the setting supported by the Vim implementation. This class **IS** mutable /// and the values will change. Setting names are case sensitive but the exposed property /// names tend to have more familiar camel case names type IVimSettings = /// Collection of settings owned by this IVimSettings instance abstract Settings: Setting list /// Try and set a setting to the passed in value. This can fail if the value does not /// have the correct type. The provided name can be the full name or abbreviation abstract TrySetValue: settingNameOrAbbrev: string -> value: SettingValue -> bool /// Try and set a setting to the passed in value which originates in string form. This /// will fail if the setting is not found or the value cannot be converted to the appropriate /// value abstract TrySetValueFromString: settingNameOrAbbrev: string -> strValue: string -> bool /// Get the value for the named setting. The name can be the full setting name or an /// abbreviation abstract GetSetting: settingNameOrAbbrev: string -> Setting option /// Raised when a Setting changes [<CLIEvent>] abstract SettingChanged: IDelegateEvent<System.EventHandler<SettingEventArgs>> and IVimGlobalSettings = + /// The local settings specified in the vim rc file, if any + abstract VimRcLocalSettings: IVimLocalSettings option with get, set + + /// The window settings specified in the vim rc file, if any + abstract VimRcWindowSettings: IVimWindowSettings option with get, set + /// Add a custom setting to the current collection abstract AddCustomSetting: name: string -> abbrevation: string -> customSettingSource: IVimCustomSettingSource -> unit /// When set, don't break inserts into multiple inserts when moving the cursor. Applies to all kinds of cursor movements, arrow keys, /// automatic movements from intellisense for example or mouse movements. abstract AtomicInsert: bool with get, set /// The multi-value option for determining backspace behavior. Valid values include /// indent, eol, start. Usually accessed through the IsBackSpace helpers abstract Backspace: string with get, set /// Opacity of the caret. This must be an integer between values 0 and 100 which /// will be converted into a double for the opacity of the caret abstract CaretOpacity: int with get, set /// List of paths which will be searched by the :cd and :ld commands abstract CurrentDirectoryPath: string with get, set /// Strongly typed list of paths which will be searched by the :cd and :ld commands abstract CurrentDirectoryPathList: PathOption list /// The clipboard option. Use the IsClipboard helpers for finding out if specific options /// are set abstract Clipboard: string with get, set /// Whether digraphs are supported in insert mode without <C-k> abstract Digraph: bool with get, set /// The parsed set of clipboard options abstract ClipboardOptions: ClipboardOptions with get, set /// Whether or not 'gdefault' is set abstract GlobalDefault: bool with get, set /// Whether or not to highlight previous search patterns matching cases abstract HighlightSearch: bool with get, set /// The number of items to keep in the history lists abstract History: int with get, set /// Whether or not we should be ignoring case in the ITextBuffer abstract IgnoreCase: bool with get, set /// Whether or not incremental searches should be highlighted and focused /// in the ITextBuffer abstract IncrementalSearch: bool with get, set /// Whether the command line should be treated as if it were in /// insert mode for the purposes of manipulating the IME abstract ImeCommand: bool with get, set /// Whether the IME coordinator is diabled abstract ImeDisable: bool with get, set /// The current state of the IME when in insert mode, or the /// value that will be restored when insert mode is next entered /// 0 - :lmap is off and IM is off /// 1 - :lmap is ON and IM is off /// 2 - :lmap is off and IM is ON abstract ImeInsert: int with get, set /// The current state of the IME in search mode, or the /// value that will be restored when search mode is next entered /// -1 - use the value of 'iminsert' instead /// 0 - :lmap is off and IM is off /// 1 - :lmap is ON and IM is off /// 2 - :lmap is off and IM is ON abstract ImeSearch: int with get, set /// Is the 'indent' option inside of Backspace set abstract IsBackspaceIndent: bool with get /// Is the 'eol' option inside of Backspace set abstract IsBackspaceEol: bool with get /// Is the 'start' option inside of Backspace set abstract IsBackspaceStart: bool with get /// Is the 'block' option inside of VirtualEdit set abstract IsVirtualEditBlock: bool with get /// Is the 'insert' option inside of VirtualEdit set abstract IsVirtualEditInsert: bool with get /// Is the 'all' option inside of VirtualEdit set abstract IsVirtualEditAll: bool with get /// Is the 'onemore' option inside of VirtualEdit set abstract IsVirtualEditOneMore: bool with get /// Is the 'b' option inside of WhichWrap set abstract IsWhichWrapSpaceLeft: bool with get /// Is the 's' option inside of WhichWrap set abstract IsWhichWrapSpaceRight: bool with get /// Is the 'h' option inside of WhichWrap set abstract IsWhichWrapCharLeft: bool with get /// Is the 'l' option inside of WhichWrap set abstract IsWhichWrapCharRight: bool with get /// Is the '<' option inside of WhichWrap set abstract IsWhichWrapArrowLeft: bool with get /// Is the '>' option inside of WhichWrap set abstract IsWhichWrapArrowRight: bool with get /// Is the '~' option inside of WhichWrap set abstract IsWhichWrapTilde: bool with get /// Is the '[' option inside of WhichWrap set abstract IsWhichWrapArrowLeftInsert: bool with get /// Is the ']' option inside of WhichWrap set abstract IsWhichWrapArrowRightInsert: bool with get /// Is the Selection setting set to a value which calls for inclusive /// selection. This does not directly track if Setting = "inclusive" /// although that would cause this value to be true abstract IsSelectionInclusive: bool with get /// Is the Selection setting set to a value which permits the selection /// to extend past the line abstract IsSelectionPastLine: bool with get /// Whether or not to insert two spaces after certain constructs in a /// join operation abstract JoinSpaces: bool with get, set /// The 'keymodel' setting abstract KeyModel: string with get, set /// The 'keymodel' in a type safe form abstract KeyModelOptions: KeyModelOptions with get, set /// The value of this option influences when a window will have a status line abstract LastStatus: int with get, set /// Whether or not the magic option is set abstract Magic: bool with get, set /// Maximum number of recursive depths which occur for a mapping abstract MaxMapDepth: int with get, set /// Whether or not the 'modeline' option is set abstract ModeLine: bool with get, set /// How many text lines to search for a modeline abstract ModeLines: int with get, set /// The 'mousemodel' setting abstract MouseModel: string with get, set /// The nrooff macros that separate paragraphs abstract Paragraphs: string with get, set /// List of paths which will be searched by the 'gf' :find, etc ... commands abstract Path: string with get, set /// Strongly typed list of path entries abstract PathList: PathOption list /// The nrooff macros that separate sections abstract Sections: string with get, set /// The name of the shell to use for shell commands abstract Shell: string with get, set /// The flag which is passed to the shell when executing shell commands abstract ShellFlag: string with get, set /// The 'showcmd' setting as in Vim abstract ShowCommand: bool with get, set abstract StartOfLine: bool with get, set /// This option determines the content of the status line. abstract StatusLine: string with get, set /// Controls the behavior of ~ in normal mode abstract TildeOp: bool with get, set /// Part of the control for key mapping and code timeout abstract Timeout: bool with get, set /// Part of the control for key mapping and code timeout abstract TimeoutEx: bool with get, set /// Timeout for a key mapping in milliseconds abstract TimeoutLength: int with get, set /// Timeout control for key mapping / code abstract TimeoutLengthEx: int with get, set /// Holds the scroll offset value which is the number of lines to keep visible /// above the cursor after a move operation abstract ScrollOffset: int with get, set /// Holds the Selection option abstract Selection: string with get, set /// Get the SelectionKind for the current settings abstract SelectionKind: SelectionKind /// Options for how select mode is entered abstract SelectMode: string with get, set /// The options which are set via select mode abstract SelectModeOptions: SelectModeOptions with get, set /// Overrides the IgnoreCase setting in certain cases if the pattern contains /// any upper case letters abstract SmartCase: bool with get, set /// Retrieves the location of the loaded VimRC file. Will be the empty string if the load /// did not succeed or has not been tried abstract VimRc: string with get, set /// Set of paths considered when looking for a .vimrc file. Will be the empty string if the /// load has not been attempted yet abstract VimRcPaths: string with get, set /// Holds the VirtualEdit string. abstract VirtualEdit: string with get, set /// Whether or not to use a visual indicator of errors instead of a beep abstract VisualBell: bool with get, set /// Which operations should wrap in the buffer abstract WhichWrap: string with get, set /// Whether or not searches should wrap at the end of the file abstract WrapScan: bool with get, set /// The key binding which will cause all IVimBuffer instances to enter disabled mode abstract DisableAllCommand: KeyInput; inherit IVimSettings /// Settings class which is local to a given IVimBuffer. This will hide the work of merging /// global settings with non-global ones and IVimLocalSettings = + abstract Defaults: IVimLocalSettings with get + /// Whether or not to auto-indent abstract AutoIndent: bool with get, set /// Whether or not to expand tabs into spaces abstract ExpandTab: bool with get, set /// Return the handle to the global IVimSettings instance abstract GlobalSettings: IVimGlobalSettings /// Whether or not to put the numbers on the left column of the display abstract Number: bool with get, set /// Formats that vim considers a number for CTRL-A and CTRL-X abstract NumberFormats: string with get, set /// The characters which represent a keyword / WordKind.NormalWord abstract IsKeyword: string with get, set /// Type safe representation of IsKeyword abstract IsKeywordCharSet: VimCharSet with get, set /// Whether or not to put relative line numbers on the left column of the display abstract RelativeNumber: bool with get, set /// The number of spaces a << or >> command will shift by abstract ShiftWidth: int with get, set /// Number of spaces a tab counts for when doing edit operations abstract SoftTabStop: int with get, set /// How many spaces a tab counts for abstract TabStop: int with get, set /// Whether list mode is enabled abstract List: bool with get, set /// Which characters escape quotes for certain motion types abstract QuoteEscape: string with get, set /// Whether or not the buffer ends with a newline abstract EndOfLine: bool with get, set /// Whether or not to fix any missing final newline abstract FixEndOfLine: bool with get, set /// Text width used when formatting text abstract TextWidth: int with get, set /// Comma separated list of strings that can start a comment line abstract Comments: string with get, set /// Is the provided NumberFormat supported by the current options abstract IsNumberFormatSupported: NumberFormat -> bool inherit IVimSettings /// Settings which are local to a given window. and IVimWindowSettings = + abstract Defaults: IVimWindowSettings with get + /// Whether or not to highlight the line the cursor is on abstract CursorLine: bool with get, set /// Return the handle to the global IVimSettings instance abstract GlobalSettings: IVimGlobalSettings /// The scroll size abstract Scroll: int with get, set /// Whether or not the window should be wrapping abstract Wrap: bool with get, set inherit IVimSettings \ No newline at end of file diff --git a/Src/VimWpf/Constants.cs b/Src/VimWpf/Constants.cs index 99010ff..8dedb6a 100644 --- a/Src/VimWpf/Constants.cs +++ b/Src/VimWpf/Constants.cs @@ -1,14 +1,15 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Vim.UI.Wpf { public static class VimWpfConstants { public const string BlockCaretFormatDefinitionName = "vsvim_blockcaret"; public const string ControlCharactersFormatDefinitionName = "vsvim_controlchar"; public const string CommandMarginFormatDefinitionName = "vsvim_commandmargin"; + public const string LineNumbersMarginName = "vsvim_linenumbers"; } } diff --git a/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMargin.cs b/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMargin.cs index 23cbcea..0d8201b 100644 --- a/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMargin.cs +++ b/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMargin.cs @@ -1,157 +1,151 @@ using System; using System.Collections.Generic; using System.Windows; using Microsoft.VisualStudio.Text.Editor; using Vim.UI.Wpf.Implementation.RelativeLineNumbers.Util; using Task = System.Threading.Tasks.Task; namespace Vim.UI.Wpf.Implementation.RelativeLineNumbers { internal sealed class RelativeLineNumbersMargin : VerticalCanvasMargin { private static readonly ICollection<Line> s_empty = new Line[0]; private readonly IWpfTextView _textView; private readonly ILineFormatTracker _formatTracker; private readonly IVimLocalSettings _localSettings; private readonly IWpfTextViewMargin _marginContainer; private readonly IProtectedOperations _protectedOperations; private readonly LineNumbersTracker _linesTracker; private readonly LineNumberDrawer _lineNumberDrawer; private readonly LineNumbersCalculator _lineNumbersCalculator; private double _width = double.NaN; private double _minWidth = 0.0; private double _maxWidth = double.PositiveInfinity; + // The VsVim line number margin is enabled whenever the native line + // number margin is enabled. public override bool Enabled => - _textView.Options.GetOptionValue(LineNumbersMarginOptions.LineNumbersMarginOptionId); + _textView.Options.GetOptionValue(DefaultTextViewHostOptions.LineNumberMarginId); internal RelativeLineNumbersMargin( IWpfTextView textView, ILineFormatTracker formatTracker, IVimLocalSettings localSettings, IWpfTextViewMargin marginContainer, IProtectedOperations protectedOperations) - : base(LineNumbersMarginOptions.LineNumbersMarginOptionName) + : base(VimWpfConstants.LineNumbersMarginName) { _textView = textView ?? throw new ArgumentNullException(nameof(textView)); _formatTracker = formatTracker ?? throw new ArgumentNullException(nameof(formatTracker)); _localSettings = localSettings ?? throw new ArgumentNullException(nameof(localSettings)); _marginContainer = marginContainer ?? throw new ArgumentNullException(nameof(marginContainer)); _protectedOperations = protectedOperations ?? throw new ArgumentNullException(nameof(protectedOperations)); _lineNumbersCalculator = new LineNumbersCalculator(_textView, _localSettings); _lineNumberDrawer = new LineNumberDrawer(Canvas, _formatTracker); _linesTracker = new LineNumbersTracker(_textView); _linesTracker.LineNumbersChanged += (x, y) => RedrawLines(); _localSettings.SettingChanged += (s, e) => UpdateVimNumberSettings(e); _textView.Options.OptionChanged += (s, e) => OnEditorOptionsChanged(e); SetVisualStudioMarginVisibility(Visibility.Hidden); if (_textView.VisualElement.IsLoaded) { RedrawLines(); } } private void SetVisualStudioMarginVisibility(Visibility visibility) { var visualStudioMargin = _marginContainer.GetTextViewMargin(PredefinedMarginNames.LineNumber); if (visualStudioMargin is IWpfTextViewMargin lineNumberMargin) { var element = lineNumberMargin.VisualElement; if (element.Visibility != visibility) { if (element.Visibility == Visibility.Visible) { _width = element.Width; _minWidth = element.MinWidth; _maxWidth = element.MaxWidth; element.Width = 0.0; element.MinWidth = 0.0; element.MaxWidth = 0.0; } else if (element.Visibility == Visibility.Hidden) { element.Width = _width; element.MinWidth = _minWidth; element.MaxWidth = _maxWidth; } element.Visibility = visibility; element.UpdateLayout(); } } } private void RedrawLines() { UpdateLines(GetNewLineNumbers()); } private void UpdateVimNumberSettings(SettingEventArgs eventArgs) { - if (_localSettings.RelativeNumber) + SetVisualStudioMarginVisibility(Visibility.Hidden); + if (_localSettings.Number || _localSettings.RelativeNumber) { - SetVisualStudioMarginVisibility(Visibility.Hidden); RedrawLines(); } - else - { - SetVisualStudioMarginVisibility(Visibility.Visible); - } } private void OnEditorOptionsChanged(EditorOptionChangedEventArgs eventArgs) { + SetVisualStudioMarginVisibility(Visibility.Hidden); if (Enabled) { - SetVisualStudioMarginVisibility(Visibility.Hidden); RedrawLines(); } - else - { - SetVisualStudioMarginVisibility(Visibility.Visible); - } } private ICollection<Line> GetNewLineNumbers() { // Avoid hard crashing when async as it will bring down all of // Visual Studio. try { Canvas.Width = _formatTracker.NumberWidth * _linesTracker.LinesCountWidthChars; return _lineNumbersCalculator.CalculateLineNumbers(); } catch (Exception ex) { var message = $"Unable to get new line numbers: {ex.Message}"; var exception = new Exception(message, ex); _protectedOperations.Report(exception); return s_empty; } } private void UpdateLines(ICollection<Line> newLineNumbers) { _lineNumberDrawer.UpdateLines(newLineNumbers); } } } diff --git a/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMarginFactory.cs b/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMarginFactory.cs index 8119889..2470c93 100644 --- a/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMarginFactory.cs +++ b/Src/VimWpf/Implementation/RelativeLineNumbers/RelativeLineNumbersMarginFactory.cs @@ -1,68 +1,68 @@ using System; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Vim.UI.Wpf.Implementation.RelativeLineNumbers { [Export(typeof(IWpfTextViewMarginProvider))] - [Name(LineNumbersMarginOptions.LineNumbersMarginOptionName)] + [Name(VimWpfConstants.LineNumbersMarginName)] [MarginContainer(PredefinedMarginNames.LeftSelection)] [Order(Before = PredefinedMarginNames.Spacer, After = PredefinedMarginNames.LineNumber)] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Document)] [TextViewRole(PredefinedTextViewRoles.EmbeddedPeekTextView)] - [DeferCreation(OptionName = LineNumbersMarginOptions.LineNumbersMarginOptionName)] + [DeferCreation(OptionName = DefaultTextViewHostOptions.LineNumberMarginName)] internal sealed class RelativeLineNumbersMarginFactory : IWpfTextViewMarginProvider { private readonly IClassificationFormatMapService _formatMapService; private readonly IClassificationTypeRegistryService _typeRegistryService; private readonly IProtectedOperations _protectedOperations; private readonly IVim _vim; [ImportingConstructor] internal RelativeLineNumbersMarginFactory( IClassificationFormatMapService formatMapService, IClassificationTypeRegistryService typeRegistryService, IProtectedOperations protectedOperations, IVim vim) { _formatMapService = formatMapService ?? throw new ArgumentNullException(nameof(formatMapService)); _typeRegistryService = typeRegistryService ?? throw new ArgumentNullException(nameof(typeRegistryService)); _protectedOperations = protectedOperations ?? throw new ArgumentNullException(nameof(protectedOperations)); _vim = vim ?? throw new ArgumentNullException(nameof(vim)); } public IWpfTextViewMargin CreateMargin( IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin marginContainer) { var textView = wpfTextViewHost?.TextView ?? throw new ArgumentNullException(nameof(wpfTextViewHost)); var vimBuffer = _vim.GetOrCreateVimBuffer(textView); var formatMap = _formatMapService.GetClassificationFormatMap(textView); var formatProvider = new LineNumberFormatTracker( textView, formatMap, _typeRegistryService); return new RelativeLineNumbersMargin( textView, formatProvider, vimBuffer.LocalSettings, marginContainer, _protectedOperations); } } } diff --git a/Src/VsVimShared/HostFactory.cs b/Src/VsVimShared/HostFactory.cs index 3cf0256..14b4f89 100644 --- a/Src/VsVimShared/HostFactory.cs +++ b/Src/VsVimShared/HostFactory.cs @@ -1,262 +1,253 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Windows.Threading; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using Vim; using Vim.Extensions; using Vim.UI.Wpf; namespace Vim.VisualStudio { /// <summary> /// Factory responsible for creating IVimBuffer instances as ITextView instances are created /// in Visual Studio /// </summary> [Export(typeof(IWpfTextViewCreationListener))] [Export(typeof(IVimBufferCreationListener))] [Export(typeof(IVsTextViewCreationListener))] [ContentType(VimConstants.ContentType)] [TextViewRole(PredefinedTextViewRoles.Editable)] internal sealed class HostFactory : IWpfTextViewCreationListener, IVimBufferCreationListener, IVsTextViewCreationListener { private readonly HashSet<IVimBuffer> _toSyncSet = new HashSet<IVimBuffer>(); private readonly Dictionary<IVimBuffer, VsCommandTarget> _vimBufferToCommandTargetMap = new Dictionary<IVimBuffer, VsCommandTarget>(); private readonly ReadOnlyCollection<ICommandTargetFactory> _commandTargetFactoryList; private readonly IDisplayWindowBrokerFactoryService _displayWindowBrokerFactoryServcie; private readonly IVim _vim; private readonly IVsEditorAdaptersFactoryService _adaptersFactory; private readonly ITextManager _textManager; private readonly IVsAdapter _adapter; private readonly IProtectedOperations _protectedOperations; private readonly IVimBufferCoordinatorFactory _bufferCoordinatorFactory; private readonly IKeyUtil _keyUtil; private readonly IEditorToSettingsSynchronizer _editorToSettingSynchronizer; private readonly IVimApplicationSettings _vimApplicationSettings; [ImportingConstructor] public HostFactory( IVim vim, IVsEditorAdaptersFactoryService adaptersFactory, IDisplayWindowBrokerFactoryService displayWindowBrokerFactoryService, ITextManager textManager, IVsAdapter adapter, IProtectedOperations protectedOperations, IVimBufferCoordinatorFactory bufferCoordinatorFactory, IKeyUtil keyUtil, IEditorToSettingsSynchronizer editorToSettingSynchronizer, IVimApplicationSettings vimApplicationSettings, [ImportMany] IEnumerable<Lazy<ICommandTargetFactory, IOrderable>> commandTargetFactoryList) { _vim = vim; _displayWindowBrokerFactoryServcie = displayWindowBrokerFactoryService; _adaptersFactory = adaptersFactory; _textManager = textManager; _adapter = adapter; _protectedOperations = protectedOperations; _bufferCoordinatorFactory = bufferCoordinatorFactory; _keyUtil = keyUtil; _editorToSettingSynchronizer = editorToSettingSynchronizer; _vimApplicationSettings = vimApplicationSettings; _commandTargetFactoryList = Orderer.Order(commandTargetFactoryList).Select(x => x.Value).ToReadOnlyCollection(); #if DEBUG VimTrace.TraceSwitch.Level = TraceLevel.Verbose; #endif // Make sure that for this _editorToSettingSynchronizer.SyncSetting(SettingSyncData.Create( DefaultWpfViewOptions.EnableHighlightCurrentLineId, WindowSettingNames.CursorLineName, false, x => SettingValue.NewToggle(x), s => s.GetToggle())); } /// <summary> /// Begin the synchronization of settings for the given IVimBuffer. It's okay if this method /// is called after synchronization is started. The StartSynchronizing method will ignore /// multiple calls and only synchronize once /// </summary> private void BeginSettingSynchronization(IVimBuffer vimBuffer) { // Protect against multiple calls if (!_toSyncSet.Remove(vimBuffer)) { return; } - // There is no UI to adjust the default for relative line numbers so - // push the current setting. - vimBuffer.TextView.Options.SetOptionValue( - LineNumbersMarginOptions.LineNumbersMarginOptionId, - vimBuffer.LocalSettings.RelativeNumber); - - // Vim doesn't consider folding an undo operation, and neither does VsVim (issue #2184). - vimBuffer.TextView.Options.SetOptionValue(DefaultTextViewOptions.OutliningUndoOptionId, false); - // We have to make a decision on whether Visual Studio or Vim settings win during the startup // process. If there was a Vimrc file then the vim settings win, else the Visual Studio ones // win. // // By the time this function is called both the Vim and Editor settings are at their final // values. We just need to decide on a winner and copy one to the other var settingSyncSource = _vimApplicationSettings.UseEditorDefaults ? SettingSyncSource.Editor : SettingSyncSource.Vim; // Synchronize any further changes between the buffers _editorToSettingSynchronizer.StartSynchronizing(vimBuffer, settingSyncSource); } private void ConnectToOleCommandTarget(IVimBuffer vimBuffer, ITextView textView, IVsTextView vsTextView) { var broker = _displayWindowBrokerFactoryServcie.GetDisplayWindowBroker(textView); var vimBufferCoordinator = _bufferCoordinatorFactory.GetVimBufferCoordinator(vimBuffer); var result = VsCommandTarget.Create(vimBufferCoordinator, vsTextView, _textManager, _adapter, broker, _keyUtil, _vimApplicationSettings, _commandTargetFactoryList); if (result.IsSuccess) { // Store the value for debugging _vimBufferToCommandTargetMap[vimBuffer] = result.Value; } // Try and install the IVsFilterKeys adapter. This cannot be done synchronously here // because Venus projects are not fully initialized at this state. Merely querying // for properties cause them to corrupt internal state and prevents rendering of the // view. Occurs for aspx and .js pages void install() => VsFilterKeysAdapter.TryInstallFilterKeysAdapter(_adapter, vimBuffer); _protectedOperations.BeginInvoke(install); } /// <summary> /// The JavaScript language service connects its IOleCommandTarget asynchronously based on events that we can't /// reasonable hook into. The current architecture of our IOleCommandTarget solution requires that we appear /// before them in order to function. This is particularly important for ReSharper behavior. /// /// The most reliable solution we could find is to find the last event that JavaScript uses which is /// OnGotAggregateFocus. Once focus is achieved we schedule a background item to then connect to IOleCommandTarget. /// This is very reliable in getting us in front of them. /// /// Long term we need to find a better solution here. /// /// This also applies to other items like HTMLXProjection. /// </summary> private void ConnectToOleCommandTargetDelayed(IVimBuffer vimBuffer, ITextView textView, IVsTextView vsTextView) { void connectInBackground() => _protectedOperations.BeginInvoke( () => ConnectToOleCommandTarget(vimBuffer, textView, vsTextView), DispatcherPriority.Background); EventHandler onFocus = null; onFocus = (sender, e) => { connectInBackground(); textView.GotAggregateFocus -= onFocus; }; if (textView.HasAggregateFocus) { connectInBackground(); } else { textView.GotAggregateFocus += onFocus; } } #region IWpfTextViewCreationListener void IWpfTextViewCreationListener.TextViewCreated(IWpfTextView textView) { // Create the IVimBuffer after loading the VimRc so that it gets the appropriate // settings if (!_vim.TryGetOrCreateVimBufferForHost(textView, out IVimBuffer vimBuffer)) { return; } // Visual Studio really puts us in a bind with respect to setting synchronization. It doesn't // have a prescribed time to apply it's own customized settings and in fact differs between // versions (2010 after TextViewCreated and 2012 is before). If we start synchronizing // before Visual Studio settings take affect then they will just overwrite the Vim settings. // // We need to pick a point where VS is done with settings. Then we can start synchronization // and change the settings to what we want them to be. // // In most cases we can just wait until IVsTextViewCreationListener.VsTextViewCreated fires // because that happens after language preferences have taken affect. Unfortunately this won't // fire for ever IWpfTextView. If the IWpfTextView doesn't have any shims it won't fire. So // we post a simple action as a backup mechanism to catch this case. _toSyncSet.Add(vimBuffer); _protectedOperations.BeginInvoke(() => BeginSettingSynchronization(vimBuffer), DispatcherPriority.Loaded); } #endregion #region IVimBufferCreationListener void IVimBufferCreationListener.VimBufferCreated(IVimBuffer vimBuffer) { var textView = vimBuffer.TextView; textView.Closed += (x, y) => { vimBuffer.Close(); _toSyncSet.Remove(vimBuffer); _vimBufferToCommandTargetMap.Remove(vimBuffer); }; } #endregion #region IVsTextViewCreationListener /// <summary> /// Raised when an IVsTextView is created. When this occurs it means a previously created /// ITextView was associated with an IVsTextView shim. This means the ITextView will be /// hooked into the Visual Studio command system and a host of other items. Setup all of /// our plumbing here /// </summary> void IVsTextViewCreationListener.VsTextViewCreated(IVsTextView vsView) { // Get the ITextView created. Shouldn't ever be null unless a non-standard Visual Studio // component is calling this function var textView = _adaptersFactory.GetWpfTextViewNoThrow(vsView); if (textView == null) { return; } if (!_vim.TryGetVimBuffer(textView, out IVimBuffer vimBuffer)) { return; } // At this point Visual Studio has fully applied it's settings. Begin the synchronization process BeginSettingSynchronization(vimBuffer); var contentType = textView.TextBuffer.ContentType; if (contentType.IsJavaScript() || contentType.IsResJSON() || contentType.IsHTMLXProjection()) { ConnectToOleCommandTargetDelayed(vimBuffer, textView, vsView); } else { ConnectToOleCommandTarget(vimBuffer, textView, vsView); } } #endregion } }
sukhitambar/testapp
807194a00e030adbfd4a8afe062ea03acd40ac3c
[Misc] new changes
diff --git a/second.rb b/second.rb index bd86ee2..4ca99d9 100644 --- a/second.rb +++ b/second.rb @@ -1 +1,3 @@ -sdafsaf \ No newline at end of file +sdafsaf sdkfhaslk +sdf askjdfa +sdf sa \ No newline at end of file
sukhitambar/testapp
d0da042b49fc57a9921661eff28ea4559434c31e
[Msc] sdfsdf
diff --git a/second.rb b/second.rb new file mode 100644 index 0000000..bd86ee2 --- /dev/null +++ b/second.rb @@ -0,0 +1 @@ +sdafsaf \ No newline at end of file
sukhitambar/testapp
f042211f024696da03e4bc8e8218a4adbd07e99a
[misc] temp
diff --git a/temp.txt b/temp.txt new file mode 100644 index 0000000..14e1af7 --- /dev/null +++ b/temp.txt @@ -0,0 +1 @@ +This is temp file \ No newline at end of file
allomov/WaveRegions
925842b6e1cb4f6835a45d34231fdb69f1836bab
There is opportunity to set regions and markers inside wav files. Various programs use it to perform time dependent data. This project helps to convert information about regiuons from wave file created in Sound Forge to text file, wich is used by Waveserfer to perform transcription.
diff --git a/RegionTypeConverter.pro b/RegionTypeConverter.pro new file mode 100644 index 0000000..6733703 --- /dev/null +++ b/RegionTypeConverter.pro @@ -0,0 +1,24 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2010-03-01T12:57:49 +# +#------------------------------------------------- + +QT -= gui + +TARGET = RegionTypeConverter +CONFIG += console +CONFIG -= app_bundle + +TEMPLATE = app + +HEADERS += RiffFile.h \ + chunk.h \ + wavefile.h \ + WaveRegionFile.h + +SOURCES += main.cpp \ + chunk.cpp \ + RiffFile.cpp \ + wavefile.cpp \ + WaveRegionFile.cpp diff --git a/RiffFile.cpp b/RiffFile.cpp new file mode 100644 index 0000000..98043d8 --- /dev/null +++ b/RiffFile.cpp @@ -0,0 +1,100 @@ +#include "RiffFile.h" + +RiffFile::RiffFile(QFile* file) +{ +// this->file = new QFile(fileName); + this->file = file; + errorsList = new QStringList; + rootChunk = NULL; +} + +RiffFile::~RiffFile(void){ + if (file->isOpen()) close(); + // delete file; + delete errorsList; +} + +bool RiffFile::open(QIODevice::OpenModeFlag flag){ + if (file->isOpen()) { + processError("RiffFile::open error: file already opened"); + return false; + } + bool ok = file->open(flag); + if (!ok) processError("RiffFile::open error: can't open file"); + return ok; +} + +bool RiffFile::close(){ + if (!file->isOpen()) {processError("RiffFile::open error: file is not opened"); return false;} + file->close(); + if (rootChunk) delete rootChunk; rootChunk = NULL; + return true; +} + +bool RiffFile::setRootChunk(Chunk* rootChunk){ + if (file->openMode() & QIODevice::ReadOnly){ + processError("RiffFile::setRootChunk error:: file can't be opened for reading"); + return false; + } + return this->rootChunk = rootChunk; +} + +QStringList RiffFile::getErrors(){ + QStringList list(*errorsList); + list += rootChunk->getErrors(); + return list; +} + +void RiffFile::processError(QString errorMessage){ + qDebug() << errorMessage; + errorsList->append(errorMessage); +} + +Chunk* RiffFile::getRootChunk(){ + if (rootChunk) + return rootChunk; + else + return createRootChunk(); +} + + +Chunk* RiffFile::createRootChunk(){ + qDebug() << file->fileName() << !file->isOpen(); + if (!file->isOpen()){ + processError("RiffFile::createRootChunk error: file is not opened"); return NULL; + } + if (!file->openMode() & QIODevice::ReadOnly & QIODevice::WriteOnly){ + processError("RiffFile::createRootChunk error: doesn't support reading and writing in a same time"); return NULL; + } + + if (rootChunk ) delete rootChunk ; + rootChunk = new Chunk(file); + + if (file->openMode() & QIODevice::ReadOnly){ + rootChunk->read(); + } + if (file->openMode() & QIODevice::WriteOnly){ + + } + return rootChunk; +} + + +Chunk* RiffFile::findChunkByName(QString name, uint pos){ + if (rootChunk) { + ChunkList* list = rootChunk->getChildren(); + Chunk* ch; + int n = 0; + foreach(ch, *list){ + if (ch->getName()==name) { + if (n==pos) return ch; else n++; + } + } + } + return NULL; +} + +bool RiffFile::readChunks(void){ + getRootChunk(); + return true; +} diff --git a/RiffFile.h b/RiffFile.h new file mode 100644 index 0000000..95db452 --- /dev/null +++ b/RiffFile.h @@ -0,0 +1,38 @@ +#ifndef RIFFFILE_H +#define RIFFFILE_H + +#include <QtCore> +#include "chunk.h" + +using namespace RiffChunk; + +typedef unsigned short int2b; +typedef unsigned long int4b; + +class RiffFile { + +protected: + QFile* file; + QStringList* errorsList; + Chunk* rootChunk; + +public: + RiffFile(QFile* file); + ~RiffFile(void); + bool open(QIODevice::OpenModeFlag flag); + bool close(); + Chunk* getRootChunk(); + bool setRootChunk(Chunk* rootChunk); + + QStringList getErrors(); + Chunk* findChunkByName(QString name, uint pos=0); + +protected: + bool readChunks(void); + bool writeChunk(Chunk*); + void processError(QString errorMessage); + Chunk* createRootChunk(); + +}; + +#endif diff --git a/WaveRegionFile.cpp b/WaveRegionFile.cpp new file mode 100644 index 0000000..f064bc5 --- /dev/null +++ b/WaveRegionFile.cpp @@ -0,0 +1,172 @@ +#include "WaveRegionFile.h" + +using namespace RiffFileNamespace; + + +WaveRegionFile::WaveRegionFile(QFile* f) : WaveFile(f){ + regionList = new RegionList; + markerList = new MarkerList; +} + +WaveRegionFile::~WaveRegionFile(){} + +void WaveRegionFile::addRegion(myDWORD begin, myDWORD end, QString name){ + regionList->append(new Region(begin, end, name)); +} + +void WaveRegionFile::addMark(myDWORD position){ + markerList->push_back(new Mark(position)); +} +// void WaveRegionFile::createChunks(); +void WaveRegionFile::write(){ + Chunk* riff = new Chunk("RIFF", file); + ChunkList* riffChildren = riff->getChildren(); + Chunk* fmt = new Chunk("fmt ", file); + fmt->addToData(info->toBytes(), info->getBytesCount()); + riffChildren->append(fmt); + Chunk* data = new Chunk("data", file); + data->addToData(waveData->data(), waveData->size()); + riffChildren->append(data); + Chunk* cue = new Chunk("cue ", file); + riffChildren->append(cue); + + Chunk* list = new Chunk("LIST", file); + ChunkList* listChildren = list->getChildren(); + + Region* r; + + + int freeID=1; + ChunkList lables; + foreach(r, *regionList){ + myDWORD cueID = freeID++; + CuePoint cuePoint1(cueID, r->begin); + cue->addToData(cuePoint1.toBytes(cueID), cuePoint1.getBytesCount()); + + Chunk* ch = new Chunk("ltxt", file); + Byte* bytes = r->toLtxtChunkBytes(cueID); + ch->addToData(bytes, r->getLtxtByteCount()); + listChildren->append(ch); + + ch = new Chunk("labl", file); + Byte* bytes2 = r->toLablChunkBytes(cueID); + ch->addToData(bytes2, r->getLablByteCount()); + lables.append(ch); + } + *(listChildren) += lables; + + + Mark* m; + foreach(m, *markerList){ + myDWORD cueID = freeID++; + CuePoint cuePoint1(cueID, m->position); // ñîçäàåò îáúåêò cue ýëêìåíòà + cue->addToData(cuePoint1.toBytes(cueID), cuePoint1.getBytesCount()); + Chunk* ch = new Chunk("labl", file); + Byte* bytes = m->toLablChunkBytes(cueID); + ch->addToData(bytes, m->getLablByteCount()); + listChildren->append(ch); + } + +// âñòàâèòü cue Number + + riff->write(); +} + +RegionList* WaveRegionFile::getRegions(){ + return regionList; +} + +MarkerList* WaveRegionFile::getMarkers(){ + return markerList; +} + +bool WaveRegionFile::read(){ + readChunks(); + parseCueChunk(); + + int i=0; + Chunk* list; + do { + list = rootChunk->findChunkByName("LIST", i++); + } while (list!=NULL && !isRegionAndMarksList(list)); + if (list==NULL) { + ERROR_MACRO("there is no list of regions", false); + } + + ChunkList* labels = list->getChildren(); + Chunk* ch1; + + foreach(ch1, *labels){ + if (ch1->getName()=="ltxt"){ + myDWORD cueID = ch1->readDWORD(); + CuePoint* cp = findCueById(cueID); + myDWORD sampleLength = ch1->readDWORD(4); + myDWORD begin = cp->sampleOffset; + Region* r = new Region(begin, begin + sampleLength, cueID); + regionList->append(r); + } + if (ch1->getName()=="labl"){ + myDWORD cueID = ch1->readDWORD(); + + Byte* bytes; + int textSize = ch1->getDataSize(); + ch1->readData(bytes, textSize); + char* textChars = new char[textSize-4]; + memcpy(textChars, bytes+4, textSize-4); + QString text = QString::fromAscii(textChars); + + bool isConnectedWithRegion = false; + Region* r; + foreach(r, *regionList){ + if (cueID==r->cueID) { + r->name = text; + isConnectedWithRegion = true; + } + } + if (!isConnectedWithRegion){ + CuePoint* cp = findCueById(cueID); + Mark* m = new Mark(cp->sampleOffset); + markerList->append(m); + } + } + } +} + +void WaveRegionFile::parseCueChunk(){ + cuePointList = new CuePointList; + Chunk* chunk = findChunkByName("cue "); + int size = chunk->getDataSize(); + Byte* bytes = new Byte[size]; + chunk->readData(bytes, size); + myDWORD cuePointsCount; + memcpy((char*)&cuePointsCount, bytes, 4); + + for (int i=0; i<cuePointsCount; i++){ + CuePoint* cp = CuePoint::fromBytes(bytes + i*24 + 4); + cuePointList->append(cp); + } +} + +bool WaveRegionFile::isRegionAndMarksList(Chunk* ch){ + if (ch->getName().toUpper()=="LIST" && ch->getType() == "adtl"){ + ChunkList* chl = ch->getChildren(); + Chunk* ch; + foreach(ch,*chl){ + qDebug() << ch->getName(); + if (!(ch->getName()=="ltxt" || ch->getName()=="labl")){ + return false; + } + } + return true; + } + return false; +} + +CuePoint* WaveRegionFile::findCueById(myDWORD cueID){ + CuePoint* cp; + foreach(cp, *cuePointList){ + if (cp->cueID==cueID) return cp; + } + return NULL; +} + diff --git a/WaveRegionFile.h b/WaveRegionFile.h new file mode 100644 index 0000000..dc16b3d --- /dev/null +++ b/WaveRegionFile.h @@ -0,0 +1,129 @@ +#ifndef WAVEREGIONFILE_H + +#define WAVEREGIONFILE_H +#include "WaveFile.h" + +namespace RiffFileNamespace { + + struct Region { + QString name; + myDWORD begin; + myDWORD end; + myDWORD cueID; + Region(myDWORD begin, myDWORD end, myDWORD cueID){this->begin=begin; this->end=end;this->cueID=cueID;} + Region(myDWORD begin, myDWORD end, QString name=""){this->begin=begin; this->end=end; this->name=name; } + Byte* toLtxtChunkBytes(myDWORD cueID){ + Byte* bytes = new Byte(getLtxtByteCount()); + myDWORD dur = end - begin; + int2b zero = 0; + memcpy(bytes , &cueID , 4); + memcpy(bytes+4 , &dur , 4); + memcpy(bytes+8 , "rgn " , 4); + memcpy(bytes+12, &zero , 2); + memcpy(bytes+14, &zero , 2); + memcpy(bytes+16, &zero , 2); + memcpy(bytes+18, &zero , 2); + return bytes; + } + + + Byte* toLablChunkBytes(myDWORD cueID){ + Byte* bytes = new Byte(getLablByteCount()); + QByteArray text = name.toLocal8Bit(); + memcpy(bytes , &cueID , 4); + memcpy(bytes+4 , text.data(), text.size()); + return bytes; + } + + myDWORD getLtxtByteCount(){ + return 20; + } + + myDWORD getLablByteCount(){ + return 20 + name.length(); + } + + }; + + struct CuePoint { + CuePoint() {} + CuePoint(myDWORD id, myDWORD sampleOffset) {cueID=id; this->sampleOffset=sampleOffset;} + myDWORD cueID; + myDWORD sampleOffset; + Byte* toBytes(myDWORD cueID){ //LablChunkBytes + Byte* bytes = new Byte(24); + myDWORD zero = 0; + memcpy(bytes, &cueID, 4); + memcpy(bytes+4, &zero, 4); + memcpy(bytes+8, "data", 4); + memcpy(bytes+12, &zero, 4); + memcpy(bytes+16, &zero, 4); + memcpy(bytes+20, &sampleOffset, 4); + return bytes; + } + + myDWORD getBytesCount(){ +// myDWORD d = name.length() +// return 20 + name.length() + (name.length()%2)?1:0; + return 24; + } + + static CuePoint* fromBytes(Byte* bytes){ + CuePoint* res = new CuePoint; + memcpy(&res -> cueID, bytes, 4); + memcpy(&res -> sampleOffset, bytes+20, 4); + return res; + } + + }; + + struct Mark { + myDWORD position; + myDWORD cueID; + QString text; + Mark(myDWORD pos){ + this->position = pos; + } + + Byte* toLablChunkBytes(myDWORD cueID){ + Byte* bytes = new Byte(getLablByteCount()); + char ch = '\0'; + memcpy(bytes, &cueID, 4); + memcpy(bytes+4, &ch, 1); + return bytes; + } + + myDWORD getLablByteCount(){ + return 6; + } + + }; + + typedef QVector<Region*> RegionList; + typedef QVector<Mark*> MarkerList; + typedef QVector<CuePoint*> CuePointList; + + class WaveRegionFile : public WaveFile { + private: + RegionList* regionList; + MarkerList* markerList; + CuePointList* cuePointList; + void parseCueChunk(); + CuePoint* findCueById(myDWORD cueID); + + public: + WaveRegionFile(QFile*); + ~WaveRegionFile(); + void addRegion(myDWORD begin, myDWORD end, QString name); + void addMark(myDWORD position); + void write(); + bool read(); + + MarkerList* getMarkers(); + RegionList* getRegions(); + bool isRegionAndMarksList(Chunk*); + // void createChunks(); + }; +} + +#endif diff --git a/chunk.cpp b/chunk.cpp new file mode 100644 index 0000000..1933a06 --- /dev/null +++ b/chunk.cpp @@ -0,0 +1,292 @@ +#include "chunk.h" + +using namespace RiffChunk; + +QString RiffChunk::FOURCC2QString(FOURCC d){ + char* chars = new char[5]; + *(chars+4) = '\0'; + memcpy(chars, &d, 4); + return QString::fromAscii(chars); +} + +QString RiffChunk::DWORD2QString(myDWORD d){ + char* chars = new char[5]; + *(chars+4) = '\0'; + memcpy(chars, &d, 4); + return QString::fromAscii(chars); +} + +ByteBuffer* RiffChunk::Bytes2ByteBuffer(Byte* b , uint size){ + ByteBuffer* buffer = new ByteBuffer; + for (int i=0; i<size; i++) { + buffer->append(*(b+i)); + } + return buffer; +} + + +Chunk* Chunk::copy(void){ +// this->errorsList = new QStringList(ch->getErrors()); +// this->children = ch->isList() ? new ChunkList(ch->getChildren()) : NULL; +// this->ckID = ch->getID(); +// this->ckSize = ch->getDataSize(); +// this->file = file; +// this->offset = ch->getHeaderOffset(); + return NULL; +} + +Chunk::Chunk(QString name, QFile* file){ + this->file = file; + setName(name); + init(); +} + +Chunk::Chunk(QFile* file) +{ + this->file = file; + init(); +} + +void Chunk::init(){ + errorsList = new QStringList; + children = NULL; + offset = 0; + ckSize = 0; + headerSize = 8; +} + +Chunk::~Chunk(void){ + // if (errorsList) delete errorsList; + // if (children) delete children; +} + +bool Chunk::isList(){ + QString name = getName().toUpper(); + if (name == "RIFF" || name == "LIST") return true; + return false; +} + +QString Chunk::getName(){ + return FOURCC2QString(ckID); +} + +void Chunk::setName(QString s){ + char* bytes = s.toLocal8Bit().data(); + memcpy(&ckID, bytes, 4); + if (isList()) { + children = new ChunkList; + if (getName().toUpper()=="RIFF") typeID = 0x57415645; else typeID = 0x6164746C; + } + +} + +ChunkList* Chunk::getChildren(){ + return children; +} + + +bool Chunk::write(){ + ckSize = data->size() + (isList() ? 4 : 0); + file->write((const char*) &ckID, 4); + file->write((const char*) &ckSize, 4); + file->write(data->data(), data->size()); + if (isList()){ + Chunk* ch; + foreach(ch, *children){ + ch->write(); + } + } + return true; +} + +void Chunk::addChild(Chunk* ){ + +} + + +// ñ÷èòûâàåò çàãîëîâîê ÷àíêà, è, åñëè ÷àíê ÿâëÿåòñÿ ñïèñêîì, ñ÷èòûâàåò ïîòîìêîâ +bool Chunk::read(){ + bool ok = readHeader(); + + qDebug() << "Readed header:" + <<"name:" << getName() + << "getDataSize:" << getDataSize() + << "headerOffset:" << getHeaderOffset() + << "dataOffset:" << getDataOffset() ; +// << "\tdataOffset:" << getDataOffset() << "\n"; + if (ok && isList()){ + ok = readEmbeddedList(); + } + return ok; +} + +/* + åñëè ðàçìåð íå óêàçàí, òî íà ìåñòå áàéò ñîçäàåòñÿ íîâûé ìàññèâ, êîòîðûé áóäåò ñîäåðæàòü âñå äàííûå èç ÷àíêà + ñ÷èòûâàåò ïîëå data â ÷àíêå, òî åñòü òî ÷òî èäåò ïîñëå çàãîëîâêà. + âîçâðàùàåò êîëè÷åñòâî ïðî÷èòàííûõ áàéò. +*/ +int Chunk::readData(Byte* data , myDWORD size){ + if (size==-1 && isOpenedForReading()) { + size = getDataSize(); + data = new char[size]; + } + + if (!(file->openMode() & QIODevice::ReadOnly)) + ERROR_MACRO("Chunk::readData error: file should be opened for reading", -1); + if (!checkFilePosition(getDataOffset())) + ERROR_MACRO("Chunk::readData error: there is no good in this message", -1); + return file->read(data, size); +} + +bool Chunk::readHeader() { + Byte* bytes = new Byte[8]; + if (!checkFilePosition(getHeaderOffset())) + ERROR_MACRO("Chunk::readHeader error: there is no good in this message", false); + int bytesReaded = file->read(bytes, 8); + if (bytesReaded != 8) + ERROR_MACRO("Chunk::readHeader error: readed not right bytes count", false); + memcpy(&ckID, bytes, 4); + memcpy(&ckSize, bytes+4 , 4); +// if (isList()) { +// bytesReaded = file->read(bytes, 4); +// if (bytesReaded != 4) ERROR_MACRO("Chunk::readHeader error: readed not right bytes count", false); +// memcpy(&typeID, bytes, 4); +// headerSize+=4; +// } + // qDebug() << getName(); + return true; +} + +bool Chunk::readEmbeddedList(){ + // read typeID + Byte* bytes = new Byte[4]; + int bytesReaded = file->read(bytes, 4); + if (bytesReaded != 4) + ERROR_MACRO("Chunk::readHeader error: readed not right bytes count", false); + memcpy(&typeID, bytes, 4); + this->children = new ChunkList; + int size = 0; + myDWORD cursorPosition = this->getDataOffset() + 4; + myDWORD endPosition = this->getDataOffset() + this->getDataSize() - 4; + while (cursorPosition < endPosition) { + Chunk* chunk = new Chunk(file); + chunk->setOffset(cursorPosition); + this->children->append(chunk); + chunk->read(); + cursorPosition += chunk->getHeaderSize()+chunk->getDataSize(); + } + return true; +} + +myDWORD Chunk::getHeaderSize(){ + return headerSize; +} + +myDWORD Chunk::getHeaderOffset(){ + return offset; +} + + +myDWORD Chunk::getDataOffset(){ + return offset + 8; +} + +/* + âîçâðàùàåò true åñëè óêàçàòåëü ñ÷èûâàíèÿ óñòàíîâëåí íà íóæíîé ïîçèöèè + false åñëè âîçíèêëà îøèáêà +*/ + +bool Chunk::checkFilePosition(myDWORD pos){ + // qDebug() << "pos" << pos << "file->pos()" << file->pos(); + if (file->pos() != pos){ + if (!file->seek(pos)) ERROR_MACRO(QString("Chunk::checkFilePosition error: error while trying to enter ")+ + QString::number(pos)+QString(" position"), false); + } + return true; +} + +QStringList Chunk::getErrors(){ + QStringList list(*errorsList); + if (isList()){ + Chunk* ch; + foreach(ch, *children){ + list += ch->getErrors(); + } + } + return list; +} + + +myDWORD Chunk::getDataSize() { + if (isOpenedForReading()) + return ckSize%2 ? ckSize+1 : ckSize; + else + return data->size(); +} + +FOURCC Chunk::getID() {return ckID;} + +QString Chunk::toString(){ + QString res = getName() + "\n"; + if (isList()) { + Chunk* ch; + foreach(ch, *children){ + res += "p\t" + ch->toString(); + } + } + return res; +} + +myDWORD Chunk::getOffset(void){ return offset; } +void Chunk::setOffset(myDWORD d){offset = d;} + +bool Chunk::isOpenedForReading(){ + return file->openMode() & QIODevice::ReadOnly; +} + + +bool Chunk::addToData(Byte* bytes, myDWORD size){ + for (uint i=0; i<size; i++) + data->append(*(bytes+i)); + return true; +} + +int Chunk::getSize(){ + return ckSize; +} + +ByteBuffer* Chunk::readWholeData(){ + int dataSize = getDataSize(); + Byte* bytes = new Byte[dataSize]; + readData(bytes, dataSize); + ByteBuffer* bb = Bytes2ByteBuffer(bytes, dataSize); + delete bytes; + return bb; +} + + +Chunk* Chunk::findChunkByName(QString name, uint pos){ + // ChunkList* list = rootChunk->getChildren(); + Chunk* ch; + int n = 0; + foreach(ch, *children){ + if (ch->getName().toUpper()==name.toUpper()) { + if (n==pos) return ch; else n++; + } + } + return NULL; +} + +myDWORD Chunk::readDWORD(myDWORD pos){ + if (pos>getDataSize()) + ERROR_MACRO("pos couldn`t be more than size", -1); + myDWORD positionInFile = getDataOffset() + pos; + checkFilePosition(positionInFile); + myDWORD res; + file->read((char*) &res, 4); + return res; +} + +QString Chunk::getType(){ + return DWORD2QString(typeID); +} diff --git a/chunk.h b/chunk.h new file mode 100644 index 0000000..84b3f81 --- /dev/null +++ b/chunk.h @@ -0,0 +1,101 @@ +#ifndef CHUNK_H +#define CHUNK_H + +#include <QtCore> + + +#define ERROR_MACRO(message,retVal) { \ + errorsList->append(message); \ + qDebug() << message; \ + return retVal; \ + } + + + +namespace RiffChunk { + + class Chunk; + typedef QVector<Chunk*> ChunkList; + typedef int FOURCC; // 32-bit number + typedef unsigned long myDWORD; + typedef char Byte; + typedef QVector<char> ByteBuffer; + // typedef ByteBuffer::iterator BBIterator; + + + + class Chunk + { + private: + QFile* file; + QStringList* errorsList; + + FOURCC ckID; + myDWORD ckSize; // myDWORD has my definition + myDWORD offset; + ChunkList* children; + myDWORD typeID; + myDWORD headerSize; + ByteBuffer* data; + + public: + + Chunk(QFile* file); + Chunk(QString name, QFile* file); + ~Chunk(void); + bool isList(); + ChunkList* getChildren(); + QString getName(); + void setName(QString); + + bool write(); + void addChild(Chunk* ); + + bool read(void); + int readData(Byte* data , myDWORD size=-1); + + myDWORD getHeaderOffset(void); + myDWORD getDataOffset(void); + + QStringList getErrors(void); + + myDWORD getHeaderSize(void); + myDWORD getDataSize(void); + FOURCC getID(void); + myDWORD getOffset(void); + void setOffset(myDWORD); + + int getSize(); + + QString toString(void); + Chunk* copy(void); + bool isOpenedForReading(); + + bool addToData(Byte* bytes, myDWORD size); + ByteBuffer* readWholeData(); + + Chunk* findChunkByName(QString name, uint pos=0); + + myDWORD readDWORD(myDWORD pos=0); + + QString getType(); + + protected: + bool readHeader(); + bool readEmbeddedList(); + bool checkFilePosition(myDWORD pos); + + + + private: + void init(); + }; + + QString FOURCC2QString(FOURCC d); + QString DWORD2QString(myDWORD d); + ByteBuffer* Bytes2ByteBuffer(Byte* b , uint size); +} + + + +#endif // CHUNK_H diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..62370b9 --- /dev/null +++ b/main.cpp @@ -0,0 +1,51 @@ +#include <QtCore> +#include "WaveRegionFile.h" + +using namespace RiffFileNamespace; + +double samples2time(int samples, WaveFileInfo* info){ + return ((double)samples/(double)info->sampleRate)*1000.; +} + +int main(int argc, char *argv[]) +{ +// QCoreApplication a(argc, argv); + + // argc = 2; + // argv = {"", ""}; + // argv[0] = "ZH102Y220.wav"; + // argv[1] = "regions.txt"; + if (argc==3){ + QFile file(argv[1]); + WaveRegionFile waveFile(&file); + waveFile.open(QIODevice::ReadOnly); + + waveFile.read(); + + QFile outputfile(QString::fromLocal8Bit(argv[2])); + outputfile.open(QIODevice::WriteOnly); + QTextStream out(&outputfile); + WaveFileInfo* info = waveFile.getInfo(); + RegionList* regions = waveFile.getRegions(); + Region* r; + foreach(r, *regions){ + int startInMSec = samples2time(r->begin, info)*10000.; + int endInMSec = samples2time(r->end , info)*10000.; + QString s1 = QString::number(startInMSec); + QString s2 = QString::number(endInMSec);` + + out << s1 << " " << s2 << " " << r->name << "\n"; + // QString str = durInMMs + // outputfile.write(); + } + + waveFile.close(); + outputfile.close(); +// getRootChunk + } else { + qDebug() << "there should be two paramentres: "<< + "wav file with regions and text file where to place regions info"; + } + return 0; +// return a.exec(); +} diff --git a/wavefile.cpp b/wavefile.cpp new file mode 100644 index 0000000..c8e37bf --- /dev/null +++ b/wavefile.cpp @@ -0,0 +1,112 @@ +#include "wavefile.h" + +WaveFile::WaveFile(QFile* file): RiffFile(file) +{ + info = NULL; + waveData = NULL; + WaveDataCursorPosition = 0; +} + +// don't work yet +bool WaveFile::write(){ + Chunk* dataChunk = getDataChunk(); + if (dataChunk){ + } else { + ERROR_MACRO("there is no data chunk", false); + } + return true; +} + +WaveFileInfo* WaveFile::getInfo(){ + if (info) return info; + if (file->openMode() & QIODevice::ReadOnly) { + return readInfo(); + } + return NULL; +} + +bool WaveFile::readWaveData(Byte* bytes, myDWORD bytesCount){ + Chunk* dataChunk = getDataChunk(); + if (dataChunk ){ + return dataChunk->readData(bytes, bytesCount); + } + return false; +} + +bool WaveFile::setInfo(WaveFileInfo* w) { + info = w; + if (file->openMode() & QIODevice::ReadOnly) + ERROR_MACRO("WaveFile::setInfo error: file is read only", false); + return true; +} + +bool WaveFile::addWaveData(Byte* bytes, myDWORD bytesCount){ +// qDebug("GLFunctionGraph::getValues()"); + +// QString str = QString::fromLocal8Bit("sasha molodec"); +// qDebug() << str; + + qDebug() << "Items in list"; + + for (myDWORD i=0; i<bytesCount; i++){ + Byte b = *(bytes+i); + waveData->append(b); + } + // waveData->push_back(ByteBuffer(bytes, bytesCount)); + return true; +} + +Chunk* WaveFile::getDataChunk(){ + return findChunkByName("data"); +} + +Chunk* WaveFile::getFMTChunk(){ + return findChunkByName("fmt "); +} + +WaveFileInfo* WaveFile::readInfo(){ + Chunk* fmtChunk = getFMTChunk(); + if (fmtChunk) { + Byte* bytes = new Byte[16]; + bool ok = fmtChunk->readData(bytes, 16); + if (ok) { + if (!info) info = new WaveFileInfo; + memcpy(&(info->compressionCode) , bytes, 2); + memcpy(&(info->channelsCount) , bytes + 2, 2); + memcpy(&(info->sampleRate) , bytes + 4, 4); + memcpy(&(info->bytesPerSecond) , bytes + 8, 4); + memcpy(&(info->blockAllign) , bytes + 12, 2); + memcpy(&(info->bitsPerSamle) , bytes + 14, 2); + return info; + } + } + return NULL; +} + + +void WaveFile::createChunks(){ + if (!writing()){ + rootChunk = new Chunk("RIFF", file); + ChunkList* children = rootChunk -> getChildren(); + children -> push_back(new Chunk("fmt ", file)); + children -> push_back(new Chunk("data", file)); + } else + qDebug()<<"oyjojojoyjoy"; +// ERROR_MACRO("WaveFile::createChunks error: need write mode ", ); +} + +bool WaveFile::writing() {return file->openMode() & QIODevice::WriteOnly; } +bool WaveFile::reading() {return file->openMode() & QIODevice::ReadOnly; } + +bool WaveFile::open(QIODevice::OpenModeFlag fl){ + // qDebug() << file->openMode() << (file->openMode() == QIODevice::NotOpen); + if (file->openMode() == QIODevice::NotOpen){ + bool ok = RiffFile::open(fl); + if (fl & QIODevice::WriteOnly) + this->waveData = new ByteBuffer; + qDebug() << file->fileName() << file->isOpen(); + return ok; + } else { + + } +} diff --git a/wavefile.h b/wavefile.h new file mode 100644 index 0000000..88a63ac --- /dev/null +++ b/wavefile.h @@ -0,0 +1,87 @@ +#ifndef WAVEFILE_H +#define WAVEFILE_H + +#include "RiffFile.h" + +// using namespace RiffChunk; + +// typedef unsigned int int4b; +// typedef unsigned int int2b; + +struct WaveFileInfo { + + int2b compressionCode; + int2b channelsCount; + int4b sampleRate; + int4b bytesPerSecond; + int2b blockAllign; + int2b bitsPerSamle; + + WaveFileInfo(int2b compressionCode = 1, + int2b channelsCount = 1, + int4b sampleRate = 22050, + int4b bytesPerSecond = 44100, + int2b blockAllign = 2, // êîëè÷åñòâî áàéò â ñåìïëå + int2b bitsPerSamle = 16){ + this->compressionCode = compressionCode; + this->channelsCount = channelsCount; + this->sampleRate = sampleRate; + this->bytesPerSecond = bytesPerSecond; + this->blockAllign = blockAllign; + this->bitsPerSamle = bitsPerSamle; + } + + + + Byte* toBytes(){ + Byte* bytes = new Byte(16); + memcpy(bytes, &compressionCode, 2); + memcpy(bytes+2, &channelsCount, 2); + memcpy(bytes+4, &sampleRate, 4); + memcpy(bytes+8, &bytesPerSecond, 4); + memcpy(bytes+12,&blockAllign, 2); + memcpy(bytes+14,&bitsPerSamle, 2); + return bytes; + } + + myDWORD getBytesCount(){ + return 16; + } +}; + + +class WaveFile : public RiffFile +{ + +protected: + myDWORD WaveDataCursorPosition; + WaveFileInfo* info; + ByteBuffer* waveData; + +public: + // WaveFile(QString fileName); + WaveFile(QFile* fileName); + + bool write(); + + WaveFileInfo* getInfo(); + bool readWaveData(Byte* bytes, myDWORD bytesCount); + + bool setInfo(WaveFileInfo*); + + bool addWaveData(Byte* bytes, myDWORD bytesCount); + + bool open(QIODevice::OpenModeFlag); + + +protected: + Chunk* getDataChunk(); + Chunk* getFMTChunk(); + void createChunks(); + WaveFileInfo* readInfo(); + bool writing(); + bool reading(); + +}; + +#endif // WAVEFILE_H
albertarvesu/customphpfw
fa64c202f345b52b585010115f2067692ea3fcc5
added index page
diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..e69de29
albertarvesu/customphpfw
14eca2bb499f51aff7454482e9684973976012ea
modified model
diff --git a/model/base_model.php b/model/base_model.php index dd2187c..4bed98a 100644 --- a/model/base_model.php +++ b/model/base_model.php @@ -1,85 +1,80 @@ <?php require_once dirname(__FILE__).'/../config/database.php'; require_once dirname(__FILE__).'/../util/database.php'; require_once dirname(__FILE__).'/../util/sql_helper.php'; class BaseModel { public $db = NULL; public $id = NULL; public $data = NULL; public $table = NULL; public $primary = NULL; public function __construct() { $this->db = Database::getInstance(); $this->db->connect(HOST, USERNAME, PASSWORD, DBNAME); } // getters - all and by row public function findAll($data, $cond=NULL, $order=NULL) { $sql = SqlHelper::genSelect($data, $this->table, $cond); if($order) $sql .= " ORDER BY ".$order['field']." ".$order['order']; $rs = $this->db->query($sql); if($rs && 0 < $this->db->getNumRows()) return $this->db->fetchAll($rs); return false; } public function find($data, $cond=NULL) { $sql = (is_array($data)) ? SqlHelper::genSelect($data, $this->table, $cond) : $data; $rs = $this->db->query($sql); if($rs && 0 < $this->db->getNumRows()) return $this->db->fetchRow($rs); return false; } - /* - * Is this used to find the ID of the last row inserted? If - * so, then we should change this to use mysql_insert_id() if - * we're using MySQL. [email protected] - */ public function findMax() { $sql = "SELECT MAX(".$this->primary.") AS max FROM ".$this->table; $rs = $this->db->query($sql); if($rs && 0 < $this->db->getNumRows()) return $this->db->fetchRow($rs); return false; } // updaters public function add() { $sql = SqlHelper::genInsert($this->data, $this->table); return $this->db->query($sql); } public function update() { $sql = SqlHelper::genUpdate($this->data, $this->table, $this->primary, $this->id); return $this->db->query($sql); } public function delete() { $sql = "DELETE FROM ".$this->table." WHERE ".$this->primary." = '".$this->id."';"; return $this->db->query($sql);; } // setters public function setData($data) { $this->data = $data; } public function setId($id) { $this->id = $id; } }
albertarvesu/customphpfw
c44dbd01fc578f1a1ee4895514c6b319bc9302ea
modified config
diff --git a/config/database.php b/config/database.php index 2f56407..1f8644e 100644 --- a/config/database.php +++ b/config/database.php @@ -1,6 +1,6 @@ <?php # define("HOST", "localhost"); define("HOST", "127.0.0.1"); - define("USERNAME", "root"); - define("PASSWORD", "mysql"); - define("DBNAME", "ibmedge"); + define("USERNAME", ""); + define("PASSWORD", ""); + define("DBNAME", "");
albertarvesu/customphpfw
b55cd995901d99d6bbd35e4be49a304b8ecb2f57
snippets of my custom php framework
diff --git a/README b/README index e69de29..616f08e 100644 --- a/README +++ b/README @@ -0,0 +1 @@ +Contains some snippets and the structure on how I am doing PHP web development. This is not a fully functional web framework. diff --git a/config/database.php b/config/database.php new file mode 100644 index 0000000..2f56407 --- /dev/null +++ b/config/database.php @@ -0,0 +1,6 @@ +<?php +# define("HOST", "localhost"); + define("HOST", "127.0.0.1"); + define("USERNAME", "root"); + define("PASSWORD", "mysql"); + define("DBNAME", "ibmedge"); diff --git a/controller/base_controller.php b/controller/base_controller.php new file mode 100644 index 0000000..0ad0964 --- /dev/null +++ b/controller/base_controller.php @@ -0,0 +1,63 @@ +<?php + class BaseController + { + public $data = NULL; + public $id = NULL; + public $model = NULL; + + + public function setModel($model) + { + $this->model = $model; + } + + public function setData($data) + { + $this->data = $data; + } + + public function setId($id) + { + $this->id = (int)$id; + } + + public function findAll($data=NULL, $cond=NULL, $order=NULL) + { + $data = is_array($data) ? $data : array("*"); + return $this->model->findAll($data, $cond, $order); + } + + public function find($data, $cond=NULL) + { + return $this->model->find($data, $cond); + } + + public function findMax() + { + return $this->model->findMax(); + } + + public function add() + { + $this->model->setData($this->data); + return $this->model->add(); + } + + public function update() + { + //ready for update, return the result + $this->model->setData($this->data); + $this->model->setId($this->id); + return $this->model->update(); + } + + public function delete($id) + { + if( !$id ) return false; + + $this->model->setId($id); + return $this->model->delete(); + } + + } +?> \ No newline at end of file diff --git a/model/base_model.php b/model/base_model.php new file mode 100644 index 0000000..dd2187c --- /dev/null +++ b/model/base_model.php @@ -0,0 +1,85 @@ +<?php + require_once dirname(__FILE__).'/../config/database.php'; + require_once dirname(__FILE__).'/../util/database.php'; + require_once dirname(__FILE__).'/../util/sql_helper.php'; + + class BaseModel + { + public $db = NULL; + + public $id = NULL; + public $data = NULL; + + public $table = NULL; + public $primary = NULL; + + public function __construct() + { + $this->db = Database::getInstance(); + $this->db->connect(HOST, USERNAME, PASSWORD, DBNAME); + } + + // getters - all and by row + public function findAll($data, $cond=NULL, $order=NULL) + { + $sql = SqlHelper::genSelect($data, $this->table, $cond); + if($order) $sql .= " ORDER BY ".$order['field']." ".$order['order']; + $rs = $this->db->query($sql); + if($rs && 0 < $this->db->getNumRows()) + return $this->db->fetchAll($rs); + return false; + } + + public function find($data, $cond=NULL) + { + $sql = (is_array($data)) ? SqlHelper::genSelect($data, $this->table, $cond) : $data; + $rs = $this->db->query($sql); + if($rs && 0 < $this->db->getNumRows()) + return $this->db->fetchRow($rs); + return false; + } + + /* + * Is this used to find the ID of the last row inserted? If + * so, then we should change this to use mysql_insert_id() if + * we're using MySQL. [email protected] + */ + public function findMax() + { + $sql = "SELECT MAX(".$this->primary.") AS max FROM ".$this->table; + $rs = $this->db->query($sql); + if($rs && 0 < $this->db->getNumRows()) + return $this->db->fetchRow($rs); + return false; + } + + // updaters + public function add() + { + $sql = SqlHelper::genInsert($this->data, $this->table); + return $this->db->query($sql); + } + + public function update() + { + $sql = SqlHelper::genUpdate($this->data, $this->table, $this->primary, $this->id); + return $this->db->query($sql); + } + + public function delete() + { + $sql = "DELETE FROM ".$this->table." WHERE ".$this->primary." = '".$this->id."';"; + return $this->db->query($sql);; + } + + // setters + public function setData($data) + { + $this->data = $data; + } + + public function setId($id) + { + $this->id = $id; + } + } diff --git a/util/database.php b/util/database.php new file mode 100644 index 0000000..94dc36e --- /dev/null +++ b/util/database.php @@ -0,0 +1,84 @@ +<?php + class Database + { + private static $instance = null; + private $numRows = null; + private $connect = null; + + private function __construct() + {} + + public static function getInstance() + { + if(null == self::$instance) + self::$instance = new Database(); + return self::$instance; + } + + public function connect($host, $username, $password, $dbname) + { + + if( !$this->connect = mysql_connect($host, $username, $password) ) + { + die("cannot connect to the database"); + } + + if( !$select = mysql_select_db($dbname) ) + { + die("$dbname cannot be select to the database"); + } + return $this->connect; + } + + public function query($query) + { + #die ($query); + + if( !$rs = mysql_query( $query ) ) + { + die(htmlentities($query)." cannot execute this query"); + } + + if( eregi("^SELECT",$query) ) + { + $this->numRows = mysql_num_rows($rs); + } + + //mysql_free_result($rs); + + return $rs; + } + + public function fetchAll($rs) + { + $rows = array(); + while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) ) + { + $rows[] = $row; + } + return $rows; + } + + public function fetchRow($rs) + { + if( !$row = mysql_fetch_array($rs, MYSQL_ASSOC) ) + { + die("Error fetching row"); + } + return $row; + } + + public function getNumRows() + { + return $this->numRows; + } + + public function disconnect() + { + if( !$close = mysql_close($this->connect) ) + { + die("Error closing connection"); + } + return $close; + } + } diff --git a/util/sql_helper.php b/util/sql_helper.php new file mode 100644 index 0000000..aac2785 --- /dev/null +++ b/util/sql_helper.php @@ -0,0 +1,57 @@ +<?php + class SqlHelper + { + public static function genSelect($data, $table, $cond = NULL) + { + $fields = join(', ', $data); + $cond = is_array($cond) ? SqlHelper::createEq($cond, 'AND ') : $cond; + $sql = "SELECT $fields FROM $table"; + $sql .= ($cond) ? " WHERE $cond" : ""; + return $sql; + } + + public static function genInsert($data, $table) + { + $data = SqlHelper::quote($data); + $keys = join(', ' , array_keys($data)); + $vals = join('\', \'' , array_values($data)); + return "INSERT INTO $table ({$keys}) VALUES ('{$vals}')"; + } + + public static function genUpdate($data, $table, $pri, $id, $cond = null) + { + $data = is_array($data) ? SqlHelper::createEq(SqlHelper::quote($data), ', ') : $data; + $cond = is_array($cond) ? SqlHelper::createEq($cond, 'AND ') : $cond; + $sql = "UPDATE $table SET $data WHERE $pri = '$id'"; + $sql .= ($cond) ? " AND $cond" : ""; + return $sql; + } + + private static function quote($data) + { + if(is_array($data)) + { + foreach($data as $key=>$value) + { + if(is_array($value)) + SqlHelper::quote($value); + else + $data[$key] = mysql_real_escape_string($value); + } + } + return $data; + } + + public static function createEq($data, $sep) + { + $arr = array(); + + foreach($data as $key=>$val) + { + $arr[] = "$key='$val'"; + } + return join($sep, $arr); + + } + } +?>
machida/hamcutlet-extension
dcc29f20aae5a6d2079d8f1f5d63fbacffe0fdc8
アイコン修正
diff --git a/icon.png b/icon.png index 103ff36..bb7f3f2 100644 Binary files a/icon.png and b/icon.png differ
machida/hamcutlet-extension
86ad3adcf6abe33d7998c17935680b7fe996c56b
hamcutlet chrome extension.
diff --git a/background.html b/background.html new file mode 100644 index 0000000..bae14b9 --- /dev/null +++ b/background.html @@ -0,0 +1,27 @@ +<html> +<head> +<script> + +function openTab(v) { + t = "http://hamcutlet.fjord.jp/?url=" + v; + chrome.tabs.create({url: t}); +} + +chrome.browserAction.onClicked.addListener(function(tab) { + getUrl(); +}); + +function getUrl() { + chrome.tabs.getSelected(null, function(tab) { + var url = tab.url; + if(url.match(/^http(s)?/)) { + openTab(tab.url); + } + }); +} + +</script> +</head> +<body> +</body> +</html> diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..103ff36 Binary files /dev/null and b/icon.png differ diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..f3b69e6 --- /dev/null +++ b/manifest.json @@ -0,0 +1,15 @@ +{ + "name": "Ham Cutlet Extension", + "version": "0.1", + "description": "Ham Cutletを使用したHTMLソース表示", + "background_page": "background.html", + "browser_action": { + "default_icon": "icon.png", + "defailt_title": "Ham Cutlet" + }, + "permissions": [ + "http://hamcutlet.fjord.jp/", + "http://*.google.com/", + "tabs" + ] +}
xto/SUTA
ae505fd70fda55d10a83db63f23555ae0dd2c5a5
Fixed a typo...
diff --git a/README b/README index 7ad5203..debb457 100644 --- a/README +++ b/README @@ -1,31 +1,31 @@ This is just a preliminary commit of an idea for a DSL for PHPUnit. We needed something simple to write some tests and couldn't find anything to suit our needs. What we're trying to achieve is a simple syntax for unit test and eventually driving Selenium to do UI testing. The syntax will be something like $context = new SeleniumExecutionContext("firefox","http://www.google.com"); $bob = new SeleniumDrivenUser($context); $bob->logs_in()->andThen()->fills_out(Field::username)->with("bob")-> andThen()->fills_out(Field::password)->with("qwerty")-> andThen()->clicks(Button::login)->andThen()->shouldBeLoggedin(); This type of syntax should hopefully help people who aren't developers understand and write some tests. As far as UnitTesting is concerned, we are trying to approach it with the BDD philosophy. -Using this PHPUnit ADD-ON, the testing syntax for expectations now looks like this : +Using this PHPUnit Add-On, the testing syntax for expectations now looks like this : $nicholas = new TestSubject(new DummyUser("Nicholas",true)); $nicholas->getName()->shouldEqual("Nicholas"); instead of : $nicholas = new DummyUser("Nicholas",true); $this->assertEquals( $nicholas->getName(),"Nicholas"); More to come !
xto/SUTA
2e3799cf74722715173513426b15b690d2df8179
Fixed a issue with shouldContain adn added shouldBeEmpty
diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php index 654357c..f8c51e4 100644 --- a/expectations/ExpectationsExpectations.php +++ b/expectations/ExpectationsExpectations.php @@ -1,288 +1,375 @@ <?php require_once 'src/Expectations.php'; class ExpectationsExpectations extends PHPUnit_Framework_TestCase { /** * @test */ public function ShouldBeTrueShouldBehaveJustLikeassertTrue() { Expectations::shouldBeTrue(true); self::assertTrue(true); try { self::assertTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeFalseShouldBehaveJustLikeassertFalse() { Expectations::shouldBeFalse(false); self::assertFalse(false); try { self::assertFalse(True); throw new Exception("assertFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeFalse(true); throw new Exception("shouldBeFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldEqualShouldBehaveLikeAssertEqual() { self::assertEquals("tom","tom"); Expectations::shouldEqual("tom","tom"); try { self::assertEquals("foo", "bar"); throw new Exception("assertEquals should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldEqual("foo", "bar"); throw new Exception("shouldEqual should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotBeEqualShouldBehaveLikeAssertNotEquals() { self::assertNotEquals(1,2); Expectations::shouldNotEqual(1,2); try { self::assertNotEquals(1,1); throw new Exception("assertNotEquals should fail when both elements are equal"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotEqual(1,1); throw new Expection("shouldNotEqual should fail when both elements are equal"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeNullShouldBehaveLikeAssertNull() { Expectations::shouldBeNull(null); self::assertNull(null); try { self::assertNull("Something that isn't null"); throw new Exception("assertNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeNull("Something that isn't null"); throw new Exception("shouldBeNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotBeNullShouldBehaveLikeAssertNotNull() { self::assertNotNull("Something not null"); Expectations::shouldNotBeNull("Something not null"); try { self::assertNotNull(null); throw new Exception("assertNotNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotBeNull(null); throw new Exception("shoulNotdBeNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldContainShouldBehaveLikeAssertContains() { self::assertContains("tom","tom petty"); Expectations::shouldContain("tom", "tom petty"); try { self::assertContains("tom", "petty"); throw new Exception("assertContains should fail if the pattern is not in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldContain("tom", "petty"); - throw new Exception("shoulContain should fail if the pattern is not in the value"); + throw new Exception("shoudlContain should fail if the pattern is not in the value"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + } + + /** + * @test + */ + public function ShouldContainShouldFailOnEmptyStringsAsThePattern() + { + try { + Expectations::shouldContain("", "TOM"); + throw new Exception("shoudlContain should fail if the pattern is an empty string"); + } + catch (PHPUnit_Framework_Exception $e) + { + Expectations::shouldContain("shouldBeEmpty", $e->getMessage()); + } + } + + /** + * @test + */ + public function ShouldContainShouldSucceedWhenLookingForAPatterninAnEmptyString() + { + try { + Expectations::shouldContain("tom", ""); + throw new Exception("shoudlContain should fail if the pattern is not in the value and the value is empty"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotContainShouldBehaveLikeAssertNotContains() { self::assertNotContains("tom", "something else"); Expectations::shouldNotContain("tom", "something else"); try { self::assertNotContains("tom", "tom"); throw new Exception("assertNotContains should fail if the pattern is in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotContain("tom", "tom"); throw new Exception("shoulNotContain should fail if the pattern is in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldRaiseExceptionShouldPassWhenExceptationRaisedMatchsExpectedException() { $expected = new Exception("patate"); $actual = $expected; Expectations::shouldRaiseException($actual, $expected); } /** * @test */ public function ShouldRaiseExceptionShouldFailWhenExceptationRaisedDoesNotMatchExpectedException() { $expected = new Exception("potato"); $actual = new ErrorException("potato"); try { Expectations::shouldRaiseException($actual, $expected); throw new Exception("shouldRaiseException() Should Fail When Exceptation Raised Does Not Match Expected Exception"); }catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldEqualShouldPassWhenTheTwoObjectsAreExactlyTheSame() { $Nick = new DummyUser("Nick",true); $Xavier = new DummyUser("Xavier", false); $Francis = new DummyUser("Francis", true); $expected = array($Nick, $Xavier, $Francis); $actual = array($Nick,$Xavier,$Francis); Expectations::shouldEqual($actual,$expected); } /** * @test */ public function ShouldEqualShouldFailWhenTheTwoObjectsAreNotExactlyTheSame() { $Nick = new DummyUser("Nick",true); $Xavier = new DummyUser("Xavier", false); $Francis = new DummyUser("Francis", true); $expected = array($Nick, $Xavier, $Francis); $actual = array($Xavier,$Francis); try{ Expectations::shouldEqual($actual,$expected); - throw new Expection("shouldNotEqual should fail when both elements are equal"); + throw new Exception("shouldNotEqual should fail when both elements are equal"); + } + catch(PHPUnit_Framework_ExpectationFailedException $e) + {} + } + + /** + * @test + */ + public function ShouldBeEmptyShouldSucceedWhenUsingOnEmptyString() + { + Expectations::shouldBeEmpty(""); + } + + /** + * @test + */ + public function ShouldBeEmptyShouldSucceedWhenUsingOnEmptyArray() + { + Expectations::shouldBeEmpty(array()); + } + + + /** + * @test + */ + public function ShouldBeEmptyShouldFailWhenOnNotEmptyString() + { + try{ + Expectations::shouldBeEmpty("This is not empty"); + throw new Expection("shouldBeEmpty should fail when object is not empty"); } catch(PHPUnit_Framework_ExpectationFailedException $e) {} } + /** + * @test + */ + public function ShouldBeEmptyShouldFailWhenUsedOnNotEmptyArray() + { + try + { + Expectations::shouldBeEmpty(array(1,2,3,4)); + throw new Expection("shouldBeEmpty should fail when object is not empty"); + } + catch(PHPUnit_Framework_ExpectationFailedException $e) + {} + } + /** + * @test + */ + public function ShouldBeEmptyShouldFailWhenUsedOnZero() + { + try + { + Expectations::shouldBeEmpty(0); + throw new Exception("shouldBeEmpty should fail when object is a zero"); + } + catch(PHPUnit_Framework_Exception $e) + { + Expectations::shouldContain("shouldEqual",$e->getMessage()); + } + } } ?> \ No newline at end of file diff --git a/src/Expectations.php b/src/Expectations.php index 96d95be..96ce686 100644 --- a/src/Expectations.php +++ b/src/Expectations.php @@ -1,72 +1,90 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; class Expectations extends PHPUnit_Framework_Assert { public static function shouldBeTrue($value, $message="") { self::assertThat($value, self::isTrue(), $message); } public static function shouldBeFalse($value, $message="") { self::assertThat($value, self::isFalse(), $message); } public static function shouldEqual($actual, $expected, $message = '') { self::assertEquals($expected, $actual, $message); } public static function shouldNotEqual($actual, $expected, $message = '') { self::assertNotEquals($expected, $actual, $message); } public static function shouldBeNull($value, $message = '') { self::assertNull($value, $message); } public static function shouldNotBeNull($value, $message = '') { self::assertNotNull($value, $message); } public static function shouldContain($pattern, $value, $message = '') { + if(empty($pattern)) + { + throw new PHPUnit_Framework_Exception("Your pattern is an empty string. Use shouldBeEmpty() if that is what you really wanted."); + } self::assertContains($pattern, $value, $message); } public static function shouldNotContain($pattern, $value, $message = '') { self::assertNotContains($pattern, $value, $message); } - + public static function shouldRaiseException($actual, $expected, $message="") { self::assertEquals(get_class($actual),get_class($expected), $message); } + public static function shouldBeEmpty($value, $message = 'Value is not empty') + { + if(is_numeric($value) && !is_string($value)) + { + throw new PHPUnit_Framework_Exception("The value is a numeric. Maybe you wanted to use shouldEqual or shouldNotEqual"); + } + + if(is_bool($value)) + { + throw new PHPUnit_Framework_Exception("The value is a Boolean. Maybe you wanted to use shouldBeFalse or shouldBeTrue"); + } + self::assertTrue(empty($value),$message); + } + } ?>
xto/SUTA
e64864bc732ad24397b231cc4c78ac6bc30f42cd
Downgraded required PHP Version .
diff --git a/package.xml b/package.xml index 8c5f385..446336f 100644 --- a/package.xml +++ b/package.xml @@ -1,61 +1,61 @@ <?xml version="1.0" encoding="UTF-8"?> <package packagerversion="0.1.7" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> <name>SUTA</name> <channel>pear.php.net</channel> <summary>DSL for PHPUnit and Selenium</summary> <description>Simplfied Unit Test Addon for PHPUnit that allow a natural language syntax</description> <lead> <name>Xavier Tô</name> <user>xto</user> <email>[email protected]</email> <active>yes</active> </lead> <lead> <name>nicholas Lemay</name> <user>nichoalslemay</user> <email>[email protected]</email> <active>yes</active> </lead> <lead> <name>Francis Falardeau</name> <user>ffalardeau</user> <email>[email protected]</email> <active>yes</active> </lead> <date>2010-03-16</date> <time>10:35:00</time> <version> <release>0.1.7</release> <api>0.1.7</api> </version> <stability> <release>beta</release> <api>beta</api> </stability> <license>GPL</license> <notes> http://github.com/xto/SUTA </notes> <contents> <dir name="/"> <file name="/SUTA/src/Expectations.php" role="php" /> <file name="/SUTA/src/TestSubject.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumDrivenUser.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumActions.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumExecutionContext.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumExpectations.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumExtendedDriver.php" role="php" /> </dir> </contents> <dependencies> <required> <php> - <min>5.2.9</min> + <min>5.2.5</min> </php> <pearinstaller> <min>1.9.0</min> </pearinstaller> </required> </dependencies> <phprelease /> </package>
xto/SUTA
3deb27ac5b8ab6b56f8755350d2ddd50157cb60c
updating package.xml to reflect upcomiong package Please enter the commit message for your changes. Lines starting
diff --git a/package.xml b/package.xml index f957d99..8c5f385 100644 --- a/package.xml +++ b/package.xml @@ -1,61 +1,61 @@ <?xml version="1.0" encoding="UTF-8"?> -<package packagerversion="0.1.4" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> +<package packagerversion="0.1.7" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> <name>SUTA</name> <channel>pear.php.net</channel> <summary>DSL for PHPUnit and Selenium</summary> <description>Simplfied Unit Test Addon for PHPUnit that allow a natural language syntax</description> <lead> <name>Xavier Tô</name> <user>xto</user> <email>[email protected]</email> <active>yes</active> </lead> <lead> <name>nicholas Lemay</name> <user>nichoalslemay</user> <email>[email protected]</email> <active>yes</active> </lead> <lead> <name>Francis Falardeau</name> <user>ffalardeau</user> <email>[email protected]</email> <active>yes</active> </lead> - <date>2010-03-04</date> - <time>10:53:00</time> + <date>2010-03-16</date> + <time>10:35:00</time> <version> - <release>0.1.4</release> - <api>0.1.4</api> + <release>0.1.7</release> + <api>0.1.7</api> </version> <stability> <release>beta</release> <api>beta</api> </stability> <license>GPL</license> <notes> http://github.com/xto/SUTA </notes> <contents> <dir name="/"> <file name="/SUTA/src/Expectations.php" role="php" /> <file name="/SUTA/src/TestSubject.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumDrivenUser.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumActions.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumExecutionContext.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumExpectations.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumExtendedDriver.php" role="php" /> </dir> </contents> <dependencies> <required> <php> <min>5.2.9</min> </php> <pearinstaller> <min>1.9.0</min> </pearinstaller> </required> </dependencies> <phprelease /> </package>
xto/SUTA
adf7e9fd680f8b873ea3342e9e71266322a889f5
Converted constant into string like they should of been Please enter the commit message for your changes. Lines starting
diff --git a/src/TestSubject.php b/src/TestSubject.php index 2460a09..65ab0cc 100644 --- a/src/TestSubject.php +++ b/src/TestSubject.php @@ -1,55 +1,55 @@ l<?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once dirname(__FILE__).'/Expectations.php'; class TestSubject{ private $__subject; public function __construct($subject) { $this->__subject = $subject; } function __call($method_name, $args) { if(method_exists($this->__subject, $method_name)) { return new TestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); } else if(method_exists("Expectations", $method_name)) { array_unshift($args,$this->__subject); - return call_user_func_array( array(Expectations, $method_name), $args); + return call_user_func_array( array("Expectations", $method_name), $args); } else { throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); } } public function __toString() { return (string)$this->__subject; } } ?> diff --git a/src/selenium_helper/SeleniumDrivenUser.php b/src/selenium_helper/SeleniumDrivenUser.php index 3ca5d23..e7dacd0 100644 --- a/src/selenium_helper/SeleniumDrivenUser.php +++ b/src/selenium_helper/SeleniumDrivenUser.php @@ -1,55 +1,55 @@ <?php require_once 'Testing/Selenium.php'; require_once dirname(__FILE__).'/../Expectations.php'; require_once dirname(__FILE__).'/SeleniumActions.php'; require_once dirname(__FILE__).'/SeleniumExpectations.php'; class SeleniumDrivenUser { private $__seleniumExecutionContext; private $__seleniumActions; private $__seleniumExpectations; public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext = $seleniumExecutionContext; $this->__seleniumActions = new SeleniumActions($this->__seleniumExecutionContext); $this->__seleniumExpectations = new SeleniumExpectations($this->__seleniumExecutionContext); $this->__seleniumExecutionContext->initialize(); } public function destroy() { $this->__seleniumExecutionContext->destroy(); } - + public function setJavascriptLibrary($javascriptLibrary) { - $this->__seleniumExecutionContext->setJavascriptLibrary($javascriptLibrary); + $this->__seleniumExecutionContext->setJavascriptLibrary($javascriptLibrary); } - + function __call($method_name, $args) { if(method_exists($this->__seleniumActions, $method_name)) { call_user_func_array( array($this->__seleniumActions, $method_name), $args); return $this; } - else if(method_exists(SeleniumExpectations, $method_name)) + else if(method_exists("SeleniumExpectations", $method_name)) { call_user_func_array( array($this->__seleniumExpectations, $method_name), $args); return $this; } else { throw new Exception('Unknown method '.$method_name."called on ".get_class($this)." instance."); } } } ?> \ No newline at end of file
xto/SUTA
331f497bcadf5b56772a626e252f1f6085719635
Corrected class to expectations. PHP converted the constant intro a string in previous version which raised a warning.
diff --git a/src/TestSubject.php b/src/TestSubject.php index aa73ba9..2460a09 100644 --- a/src/TestSubject.php +++ b/src/TestSubject.php @@ -1,55 +1,55 @@ -<?php +l<?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once dirname(__FILE__).'/Expectations.php'; class TestSubject{ private $__subject; public function __construct($subject) { $this->__subject = $subject; } function __call($method_name, $args) { if(method_exists($this->__subject, $method_name)) { return new TestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); } - else if(method_exists(Expectations, $method_name)) + else if(method_exists("Expectations", $method_name)) { array_unshift($args,$this->__subject); return call_user_func_array( array(Expectations, $method_name), $args); } else { throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); } } public function __toString() { return (string)$this->__subject; } } ?>
xto/SUTA
dedd63038364e81d56b73f26e84b6a608b646560
corrected include path
diff --git a/src/TestSubject.php b/src/TestSubject.php index 16bb17e..aa73ba9 100644 --- a/src/TestSubject.php +++ b/src/TestSubject.php @@ -1,55 +1,55 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -*/ - require_once 'Expectations.php'; - +*/ + require_once dirname(__FILE__).'/Expectations.php'; + class TestSubject{ private $__subject; public function __construct($subject) { - $this->__subject = $subject; - + $this->__subject = $subject; + } function __call($method_name, $args) { if(method_exists($this->__subject, $method_name)) { return new TestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); } else if(method_exists(Expectations, $method_name)) { - array_unshift($args,$this->__subject); + array_unshift($args,$this->__subject); return call_user_func_array( array(Expectations, $method_name), $args); } else { - throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); + throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); } } public function __toString() { return (string)$this->__subject; } } ?>
xto/SUTA
5ee4aa74787871a474ea374022e48da992b1decc
Added uncheck action and expectation plsu their tests.
diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php index 8d0a0a3..759f800 100644 --- a/expectations/ExpectationsSuite.php +++ b/expectations/ExpectationsSuite.php @@ -1,43 +1,43 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; require_once 'expectations/ExpectationsExpectations.php'; require_once 'expectations/TestSubjectExpectations.php'; require_once 'expectations/selenium_expectations/SeleniumDrivenUserExpectations.php'; require_once 'expectations/selenium_expectations/SeleniumActionsExpectations.php'; class ExpectationsSuite { public static function suite() { $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); $suite->addTestSuite('ExpectationsExpectations'); $suite->addTestSuite('TestSubjectExpectations'); - $suite->addTestSuite('SeleniumActionsExpectations'); + $suite->addTestSuite('SeleniumActionsExpectations'); $suite->addTestSuite('SeleniumDrivenUserExpectations'); return $suite; } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumActionsExpectations.php b/expectations/selenium_expectations/SeleniumActionsExpectations.php index 4265a8a..f33be8f 100644 --- a/expectations/selenium_expectations/SeleniumActionsExpectations.php +++ b/expectations/selenium_expectations/SeleniumActionsExpectations.php @@ -1,55 +1,59 @@ <?php require_once 'PHPUnit/Framework.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; require_once 'src/selenium_helper/SeleniumActions.php'; require_once 'src/Expectations.php'; class SeleniumActionsExpectations extends PHPUnit_Framework_TestCase { public function setUp() { $browser = 'firefox'; $url = 'http://some.url'; $timeout = 10000; } /** * @test */ public function waitsForAjaxShouldCallWaitForConditionWithjQueryConditionWhenjQueryIsTheLibrary() { $mock_seleniumExecutionContext = $this->getMock('SeleniumExecutionContext',array('getSelenium'),array($browser, $url, 'jQuery')); $mock_selenium = $this->getMock('SeleniumExtendedDriver',array(),array($browser, $url)); $mock_seleniumExecutionContext->expects($this->any())->method('getSelenium') ->will($this->returnValue($mock_selenium)); $seleniumActions = new SeleniumActions($mock_seleniumExecutionContext); $mock_selenium->expects($this->once())->method('waitForCondition') ->with("selenium.browserbot.getCurrentWindow().jQuery.active == 0"); $seleniumActions->waitsForAjax($timeout); } /** * @test */ public function waitsForAjaxShouldCallWaitForConditionWithPrototypeConditionWhenPrototypeIsTheLibrary() { $mock_seleniumExecutionContext = $this->getMock('SeleniumExecutionContext',array('getSelenium'),array($browser, $url, 'Prototype')); $mock_selenium = $this->getMock('SeleniumExtendedDriver',array(),array($browser, $url)); $mock_seleniumExecutionContext->expects($this->any())->method('getSelenium') ->will($this->returnValue($mock_selenium)); $seleniumActions = new SeleniumActions($mock_seleniumExecutionContext); $mock_selenium->expects($this->once())->method('waitForCondition') ->with("selenium.browserbot.getCurrentWindow().Ajax.activeRequestCount == 0"); $seleniumActions->waitsForAjax($timeout); } + + + + } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php index 0570e99..0f6a798 100644 --- a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -1,251 +1,265 @@ <?php require_once 'src/selenium_helper/SeleniumDrivenUser.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; require_once 'configuration/Configuration.php'; class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase { private static $selenium_execution_context; private static $selenium_driven_user; private static $selenium_test_page_path; public static function setUpBeforeClass() { $configuration = new Configuration(); self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file://".self::$selenium_test_page_path, "jQuery"); self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); } public static function tearDownAfterClass() { self::$selenium_driven_user->destroy(); } public function setUp() { self::$selenium_driven_user->goesTo("file://".self::$selenium_test_page_path); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } /** * @test */ public function shouldNotSeeShouldSucceedWhenElementIsNotFound() { self::$selenium_driven_user->shouldNotSee("//*[id('id_that_dont_exist')]"); } /** * @test */ public function shouldNotSeeShouldFailWhenElementIsFound() { try { self::$selenium_driven_user->shouldNotSee("//*[id('test_span')]"); self::fail("shouldNotSee should have failed"); } catch (Exception $e) { } } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_radio']"); self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_driven_user->selects("Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_driven_user->selects("Option 2")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } /** * @test */ public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithPrototype() { $timeout = 2; self::$selenium_driven_user->setJavascriptLibrary("Prototype"); try { self::$selenium_driven_user->clicks("//a[id('test_Prototype_link')]") ->and_then()->waitsForAjax($timeout); self::fail("the waitForAjax should have timed out"); } catch(SeleniumTimedOutException $e) {} } /** * @test */ public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithjQuery() { $timeout = 5000; self::$selenium_driven_user->setJavascriptLibrary("jQuery"); self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") ->and_then()->waitsForAjax($timeout); } /** * @test */ public function waitsForAjaxShouldThrowAnExceptionWhenItTimesOutWithjQuery() { $timeout = 0; self::$selenium_driven_user->setJavascriptLibrary("jQuery"); try { self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") ->and_then()->waitsForAjax($timeout); self::fail("the waitForAjax should have timed out"); } catch(SeleniumTimedOutException $e) {} } /** * @test */ public function withValueShouldSucceedIfValueMatchesParameter() { self::$selenium_driven_user->fillsOut("//input[@id='test_input_text']")->with("value of input"); self::$selenium_driven_user->shouldSee("//input[@id='test_input_text']")->withValue("value of input"); } + + /** + * @test + */ + public function uncheckShouldUncheckACheckboxWhenCheckboxIsChecked() + { + self::$selenium_driven_user->clicks("//input[@name='test_radio']"); + self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); + + self::$selenium_driven_user->unchecks("//input[@name='test_radio']"); + self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->unchecked(); + + } + } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumActions.php b/src/selenium_helper/SeleniumActions.php index 4718175..0db5eb6 100644 --- a/src/selenium_helper/SeleniumActions.php +++ b/src/selenium_helper/SeleniumActions.php @@ -1,112 +1,117 @@ <?php class SeleniumActions { private $__seleniumExecutionContext; public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext= $seleniumExecutionContext; } private function __getLastVisitedLocation() { return $this->__seleniumExecutionContext->getLastVisitedLocation(); } private function __getSelenium() { return $this->__seleniumExecutionContext->getSelenium(); } private function __setLastVisitedLocation($location) { $this->__seleniumExecutionContext->setLastVisitedLocation($location); } private function __resetLastVisitedLocation() { $this->__seleniumExecutionContext->resetLastVisitedLocation(); } public function goesTo($url) { $this->__getSelenium()->open($url); } public function fillsOut($text_field_locator) { $this->__setLastVisitedLocation($text_field_locator); } public function with($value) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to type... Please specify where to type."); $this->__getSelenium()->type($this->__getLastVisitedLocation(), $value); $this->__resetLastVisitedLocation(); } public function clicks($locator) { $this->__getSelenium()->click($locator); } public function and_then() { } public function waitsForPageToLoad() { $this->__getSelenium()->waitForPageToLoad(30000); } public function drags($objects_locator) { $this->__setLastVisitedLocation($objects_locator); } public function dropsOn($destinations_locator) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to drop... Please specify where to drop the object."); $this->__getSelenium()->dragAndDropToObject($this->__getLastVisitedLocation(),$destinations_locator); } public function checks($checkbox_or_radio_button_locator) { - $this->clicks($checkbox_or_radio_button_locator); + $this->__getSelenium()->check($checkbox_or_radio_button_locator); + } + + public function unchecks($checkbox_or_radio_button_locator) + { + $this->__getSelenium()->uncheck($checkbox_or_radio_button_locator); } public function selects($value) { $this->__setLastVisitedLocation($value); } public function from($dropdown_list_locator) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to pick from... Please specify where to find the selection."); $this->__getSelenium()->select($dropdown_list_locator,'label='.$this->__getLastVisitedLocation()); $this->__resetLastVisitedLocation(); } public function waitsForAjax($timeout) { $javascriptLibrary = $this->__seleniumExecutionContext->getJavascriptLibrary(); $waitForAjaxCondition = call_user_func(array($this,'get'.$javascriptLibrary.'WaitForAjaxCondition')); $this->__getSelenium()->waitForCondition($waitForAjaxCondition, $timeout); } public function getjQueryWaitForAjaxCondition() { return "selenium.browserbot.getCurrentWindow().jQuery.active == 0"; } public function getPrototypeWaitForAjaxCondition() { return "selenium.browserbot.getCurrentWindow().Ajax.activeRequestCount == 0"; } } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExpectations.php b/src/selenium_helper/SeleniumExpectations.php index c770500..ea5dcbd 100644 --- a/src/selenium_helper/SeleniumExpectations.php +++ b/src/selenium_helper/SeleniumExpectations.php @@ -1,76 +1,83 @@ <?php class SeleniumExpectations { private $__seleniumExecutionContext; public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext= $seleniumExecutionContext; } private function __getLastVisitedLocation() { return $this->__seleniumExecutionContext->getLastVisitedLocation(); } private function __getSelenium() { return $this->__seleniumExecutionContext->getSelenium(); } private function __resetLastVisitedLocation() { $this->__seleniumExecutionContext->resetLastVisitedLocation(); } private function __setLastVisitedLocation($location) { $this->__seleniumExecutionContext->setLastVisitedLocation($location); } public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ Expectations::shouldBeTrue($this->__getSelenium()->isElementPresent($element_locator),$message ); $this->__setLastVisitedLocation($element_locator); } public function shouldNotSee($element_locator, $message = "Element was found! Verify that the locator is correct and that it should not be found !!!" ){ Expectations::shouldBeFalse($this->__getSelenium()->isElementPresent($element_locator),$message ); $this->__setLastVisitedLocation($element_locator); } public function withText($expected_text) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldContain($expected_text,$this->__getSelenium()->getText($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } public function withValue($expected_text) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldContain($expected_text,$this->__getSelenium()->getValue($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } public function checked() { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldBeTrue($this->__getSelenium()->isChecked($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } + public function unchecked() + { + Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); + Expectations::shouldBeFalse($this->__getSelenium()->isChecked($this->__getLastVisitedLocation())); + $this->__resetLastVisitedLocation(); + } + public function selected() { Expectations::shouldEqual($this->__getSelenium()->getValue($this->__getLastVisitedLocation()), $this->__getSelenium()->getSelectedLabel($this->__getLastVisitedLocation()."/..")); $this->__resetLastVisitedLocation(); } public function shouldBeOnPage($expected_url) { Expectations::shouldEqual($this->__getSelenium()->getLocation(), $expected_url); } } ?>
xto/SUTA
7b702eb79ddc1f23570147efdfb00f2df62cd96f
Added a withValue expectation
diff --git a/configuration/Configuration.php b/configuration/Configuration.php index d2e93ad..95f77f9 100644 --- a/configuration/Configuration.php +++ b/configuration/Configuration.php @@ -1,11 +1,11 @@ <?php class Configuration { - private $SUTA_path = "/home/xto/projects/SUTA/"; + private $SUTA_path = "/home/smpdev/SUTA/"; private $selenium_test_page_path = "expectations/selenium_expectations/selenium_test_page.html"; public function getSeleniumTestPagePath() { return $this->SUTA_path.$this->selenium_test_page_path; } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php index 0acc492..0570e99 100644 --- a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -1,240 +1,251 @@ <?php require_once 'src/selenium_helper/SeleniumDrivenUser.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; require_once 'configuration/Configuration.php'; class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase { private static $selenium_execution_context; private static $selenium_driven_user; private static $selenium_test_page_path; public static function setUpBeforeClass() { $configuration = new Configuration(); self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file://".self::$selenium_test_page_path, "jQuery"); self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); } public static function tearDownAfterClass() { self::$selenium_driven_user->destroy(); } public function setUp() { self::$selenium_driven_user->goesTo("file://".self::$selenium_test_page_path); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } /** * @test */ public function shouldNotSeeShouldSucceedWhenElementIsNotFound() { self::$selenium_driven_user->shouldNotSee("//*[id('id_that_dont_exist')]"); } /** * @test */ public function shouldNotSeeShouldFailWhenElementIsFound() { try { self::$selenium_driven_user->shouldNotSee("//*[id('test_span')]"); self::fail("shouldNotSee should have failed"); } catch (Exception $e) { } } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_radio']"); self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_driven_user->selects("Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_driven_user->selects("Option 2")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } + + /** + * @test + */ + public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithPrototype() + { + $timeout = 2; + self::$selenium_driven_user->setJavascriptLibrary("Prototype"); + + try + { + self::$selenium_driven_user->clicks("//a[id('test_Prototype_link')]") + ->and_then()->waitsForAjax($timeout); + + self::fail("the waitForAjax should have timed out"); + } + catch(SeleniumTimedOutException $e) + {} + } + /** * @test */ public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithjQuery() { $timeout = 5000; self::$selenium_driven_user->setJavascriptLibrary("jQuery"); self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") ->and_then()->waitsForAjax($timeout); } - + /** * @test */ public function waitsForAjaxShouldThrowAnExceptionWhenItTimesOutWithjQuery() { $timeout = 0; self::$selenium_driven_user->setJavascriptLibrary("jQuery"); try { self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") ->and_then()->waitsForAjax($timeout); self::fail("the waitForAjax should have timed out"); } catch(SeleniumTimedOutException $e) {} } - + /** * @test */ - public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithPrototype() - { - $timeout = 0; - self::$selenium_driven_user->setJavascriptLibrary("Prototype"); - - try - { - self::$selenium_driven_user->clicks("//a[id('test_Prototype_link')]") - ->and_then()->waitsForAjax($timeout); - - self::fail("the waitForAjax should have timed out"); - } - catch(SeleniumTimedOutException $e) - {} + public function withValueShouldSucceedIfValueMatchesParameter() + { + self::$selenium_driven_user->fillsOut("//input[@id='test_input_text']")->with("value of input"); + + self::$selenium_driven_user->shouldSee("//input[@id='test_input_text']")->withValue("value of input"); } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/selenium_test_page.html b/expectations/selenium_expectations/selenium_test_page.html index ddce0e6..08980b4 100644 --- a/expectations/selenium_expectations/selenium_test_page.html +++ b/expectations/selenium_expectations/selenium_test_page.html @@ -1,57 +1,62 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.sleep.js" ></script> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('#test_jQuery_link').click(function() { jQuery.active = 1; - jQuery.sleep(3, function() + jQuery.sleep(5, function() { jQuery.active = 0; }); } ); jQuery('#test_Prototype_link').click(function() + { + Ajax.activeRequestCount = 1; + jQuery.sleep(5, function() { - Ajax.activeRequestCount = 1; - jQuery.sleep(3, function() - { - Ajax.activeRequestCount = 0; - }); - } -); + Ajax.activeRequestCount = 0; + }); + } + ); }); </script> </head> <body> <span id="test_span">Text</span> <br /> <label for='test_checkbox'>Checkbox</label><input name="test_checkbox" type="checkbox"/> <br /> <label for='test_radio'>Radio</label><input name="test_radio" type="radio"/> <br /> <label for=test_select">Select</label> <select id="test_select"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> <br /> <label for="test_textfield">Text field</label> <input type="text" /> <br /> <br /> <a id="test_jQuery_link" href="#" >jQuery ajax Link</a> +<br /> <a id="test_Prototype_link" href="#" >Prototype ajax Link</a> +<br /> +<br /> +<label for="test_input_text"></label> +<input id="test_input_text" type="text" /> </body> </html> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExpectations.php b/src/selenium_helper/SeleniumExpectations.php index 53cde06..c770500 100644 --- a/src/selenium_helper/SeleniumExpectations.php +++ b/src/selenium_helper/SeleniumExpectations.php @@ -1,69 +1,76 @@ <?php class SeleniumExpectations { private $__seleniumExecutionContext; public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext= $seleniumExecutionContext; } private function __getLastVisitedLocation() { return $this->__seleniumExecutionContext->getLastVisitedLocation(); } private function __getSelenium() { return $this->__seleniumExecutionContext->getSelenium(); } private function __resetLastVisitedLocation() { $this->__seleniumExecutionContext->resetLastVisitedLocation(); } private function __setLastVisitedLocation($location) { $this->__seleniumExecutionContext->setLastVisitedLocation($location); } public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ Expectations::shouldBeTrue($this->__getSelenium()->isElementPresent($element_locator),$message ); $this->__setLastVisitedLocation($element_locator); } public function shouldNotSee($element_locator, $message = "Element was found! Verify that the locator is correct and that it should not be found !!!" ){ Expectations::shouldBeFalse($this->__getSelenium()->isElementPresent($element_locator),$message ); $this->__setLastVisitedLocation($element_locator); } public function withText($expected_text) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldContain($expected_text,$this->__getSelenium()->getText($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } + public function withValue($expected_text) + { + Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); + Expectations::shouldContain($expected_text,$this->__getSelenium()->getValue($this->__getLastVisitedLocation())); + $this->__resetLastVisitedLocation(); + } + public function checked() { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldBeTrue($this->__getSelenium()->isChecked($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } public function selected() { Expectations::shouldEqual($this->__getSelenium()->getValue($this->__getLastVisitedLocation()), $this->__getSelenium()->getSelectedLabel($this->__getLastVisitedLocation()."/..")); $this->__resetLastVisitedLocation(); } public function shouldBeOnPage($expected_url) { Expectations::shouldEqual($this->__getSelenium()->getLocation(), $expected_url); } } ?>
xto/SUTA
f2b6d1d966ba2a1f83138f7ec1a7fb94235861a7
Fixed a bad include...
diff --git a/src/selenium_helper/SeleniumExecutionContext.php b/src/selenium_helper/SeleniumExecutionContext.php index 628c79d..b66c70c 100644 --- a/src/selenium_helper/SeleniumExecutionContext.php +++ b/src/selenium_helper/SeleniumExecutionContext.php @@ -1,89 +1,89 @@ <?php - require_once 'src/selenium_helper/SeleniumExtendedDriver.php'; + require_once dirname(__FILE__).'/SeleniumExtendedDriver.php'; class SeleniumExecutionContext { private $__browser; private $__website; private $__selenium; private $__isInitialized; private $__lastVisitedLocation; private $__javascript_library; public function __construct($browser, $website, $javascript_library) { $this->__browser = $browser; $this->__website = $website; $this->__javascript_library = $javascript_library; $this->__selenium = new SeleniumExtendedDriver($browser, $website); $this->__isInitialized = false; $this->resetLastVisitedLocation(); } public function getBrowser() { return $this->__browser; } public function getWebSite() { return $this->__website; } public function getJavascriptLibrary() { return $this->__javascript_library; } - + public function setJavascriptLibrary($javascriptLibrary) { $this->__javascript_library = $javascriptLibrary; } public function getSelenium() { return $this->__selenium; } public function setLastVisitedLocation($location) { $this->__lastVisitedLocation = $location; } public function getLastVisitedLocation() { return $this->__lastVisitedLocation; } public function resetLastVisitedLocation() { $this->__lastVisitedLocation = null; } public function initialize() { if(!$this->__isInitialized) $this->__startSelenium(); } public function destroy() { if($this->__isInitialized) $this->__stopSelenium(); } private function __startSelenium() { $this->__selenium->start(); $this->__isInitialized = true; } private function __stopSelenium() { $this->__selenium->close(); $this->__selenium->stop(); } } ?> \ No newline at end of file
xto/SUTA
23acd4118c897db3a9cf471c74ba76ddadee8c30
Added negative tests cases for waitForAjax (jQuery and Prototype)
diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php index b567421..0acc492 100644 --- a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -1,215 +1,240 @@ <?php require_once 'src/selenium_helper/SeleniumDrivenUser.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; require_once 'configuration/Configuration.php'; class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase { private static $selenium_execution_context; private static $selenium_driven_user; private static $selenium_test_page_path; public static function setUpBeforeClass() { $configuration = new Configuration(); self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file://".self::$selenium_test_page_path, "jQuery"); self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); } public static function tearDownAfterClass() { self::$selenium_driven_user->destroy(); } public function setUp() { self::$selenium_driven_user->goesTo("file://".self::$selenium_test_page_path); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } /** * @test */ public function shouldNotSeeShouldSucceedWhenElementIsNotFound() { self::$selenium_driven_user->shouldNotSee("//*[id('id_that_dont_exist')]"); } /** * @test */ public function shouldNotSeeShouldFailWhenElementIsFound() { try { self::$selenium_driven_user->shouldNotSee("//*[id('test_span')]"); self::fail("shouldNotSee should have failed"); } catch (Exception $e) { } } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_radio']"); self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_driven_user->selects("Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_driven_user->selects("Option 2")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } /** * @test */ public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithjQuery() { $timeout = 5000; self::$selenium_driven_user->setJavascriptLibrary("jQuery"); self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") ->and_then()->waitsForAjax($timeout); } + /** + * @test + */ + public function waitsForAjaxShouldThrowAnExceptionWhenItTimesOutWithjQuery() + { + $timeout = 0; + self::$selenium_driven_user->setJavascriptLibrary("jQuery"); + try + { + self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") + ->and_then()->waitsForAjax($timeout); + self::fail("the waitForAjax should have timed out"); + } + catch(SeleniumTimedOutException $e) + {} + } + /** * @test */ public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithPrototype() { - $timeout = 5000; + $timeout = 0; self::$selenium_driven_user->setJavascriptLibrary("Prototype"); - self::$selenium_driven_user->clicks("//a[id('test_Prototype_link')]") - ->and_then()->waitsForAjax($timeout); + + try + { + self::$selenium_driven_user->clicks("//a[id('test_Prototype_link')]") + ->and_then()->waitsForAjax($timeout); + + self::fail("the waitForAjax should have timed out"); + } + catch(SeleniumTimedOutException $e) + {} } } ?> \ No newline at end of file
xto/SUTA
9f12e41e62d6564545ef765cc41d7e80df7ff915
Added a test for prototype wait for ajax
diff --git a/configuration/Configuration.php b/configuration/Configuration.php index 95f77f9..d2e93ad 100644 --- a/configuration/Configuration.php +++ b/configuration/Configuration.php @@ -1,11 +1,11 @@ <?php class Configuration { - private $SUTA_path = "/home/smpdev/SUTA/"; + private $SUTA_path = "/home/xto/projects/SUTA/"; private $selenium_test_page_path = "expectations/selenium_expectations/selenium_test_page.html"; public function getSeleniumTestPagePath() { return $this->SUTA_path.$this->selenium_test_page_path; } } ?> \ No newline at end of file diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php index 1298c5c..8d0a0a3 100644 --- a/expectations/ExpectationsSuite.php +++ b/expectations/ExpectationsSuite.php @@ -1,43 +1,43 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; require_once 'expectations/ExpectationsExpectations.php'; require_once 'expectations/TestSubjectExpectations.php'; require_once 'expectations/selenium_expectations/SeleniumDrivenUserExpectations.php'; require_once 'expectations/selenium_expectations/SeleniumActionsExpectations.php'; class ExpectationsSuite { public static function suite() { $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); $suite->addTestSuite('ExpectationsExpectations'); $suite->addTestSuite('TestSubjectExpectations'); $suite->addTestSuite('SeleniumActionsExpectations'); - //$suite->addTestSuite('SeleniumDrivenUserExpectations'); + $suite->addTestSuite('SeleniumDrivenUserExpectations'); return $suite; } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php index 9593b70..b567421 100644 --- a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -1,205 +1,215 @@ <?php require_once 'src/selenium_helper/SeleniumDrivenUser.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; require_once 'configuration/Configuration.php'; class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase { private static $selenium_execution_context; private static $selenium_driven_user; private static $selenium_test_page_path; public static function setUpBeforeClass() { $configuration = new Configuration(); self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file://".self::$selenium_test_page_path, "jQuery"); self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); } public static function tearDownAfterClass() { self::$selenium_driven_user->destroy(); } public function setUp() { self::$selenium_driven_user->goesTo("file://".self::$selenium_test_page_path); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } /** * @test */ public function shouldNotSeeShouldSucceedWhenElementIsNotFound() { self::$selenium_driven_user->shouldNotSee("//*[id('id_that_dont_exist')]"); } /** * @test */ public function shouldNotSeeShouldFailWhenElementIsFound() { try { self::$selenium_driven_user->shouldNotSee("//*[id('test_span')]"); self::fail("shouldNotSee should have failed"); } catch (Exception $e) { } } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_radio']"); self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_driven_user->selects("Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_driven_user->selects("Option 2")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } /** * @test */ - public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuing() + public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithjQuery() { - $timeout = 5000; - - self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") - ->and_then()->waitsForAjax($timeout); - + $timeout = 5000; + self::$selenium_driven_user->setJavascriptLibrary("jQuery"); + self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") + ->and_then()->waitsForAjax($timeout); + } + + /** + * @test + */ + public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuingWithPrototype() + { + $timeout = 5000; + self::$selenium_driven_user->setJavascriptLibrary("Prototype"); + self::$selenium_driven_user->clicks("//a[id('test_Prototype_link')]") + ->and_then()->waitsForAjax($timeout); } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/selenium_test_page.html b/expectations/selenium_expectations/selenium_test_page.html index 69ee085..ddce0e6 100644 --- a/expectations/selenium_expectations/selenium_test_page.html +++ b/expectations/selenium_expectations/selenium_test_page.html @@ -1,58 +1,57 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.sleep.js" ></script> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('#test_jQuery_link').click(function() { jQuery.active = 1; jQuery.sleep(3, function() { jQuery.active = 0; }); } ); jQuery('#test_Prototype_link').click(function() { Ajax.activeRequestCount = 1; jQuery.sleep(3, function() { - alert('Prototype'); Ajax.activeRequestCount = 0; }); } ); }); </script> </head> <body> <span id="test_span">Text</span> <br /> <label for='test_checkbox'>Checkbox</label><input name="test_checkbox" type="checkbox"/> <br /> <label for='test_radio'>Radio</label><input name="test_radio" type="radio"/> <br /> <label for=test_select">Select</label> <select id="test_select"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> <br /> <label for="test_textfield">Text field</label> <input type="text" /> <br /> <br /> <a id="test_jQuery_link" href="#" >jQuery ajax Link</a> <a id="test_Prototype_link" href="#" >Prototype ajax Link</a> </body> </html> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumDrivenUser.php b/src/selenium_helper/SeleniumDrivenUser.php index c08079c..3ca5d23 100644 --- a/src/selenium_helper/SeleniumDrivenUser.php +++ b/src/selenium_helper/SeleniumDrivenUser.php @@ -1,50 +1,55 @@ <?php require_once 'Testing/Selenium.php'; require_once dirname(__FILE__).'/../Expectations.php'; require_once dirname(__FILE__).'/SeleniumActions.php'; require_once dirname(__FILE__).'/SeleniumExpectations.php'; class SeleniumDrivenUser { private $__seleniumExecutionContext; private $__seleniumActions; private $__seleniumExpectations; public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext = $seleniumExecutionContext; $this->__seleniumActions = new SeleniumActions($this->__seleniumExecutionContext); $this->__seleniumExpectations = new SeleniumExpectations($this->__seleniumExecutionContext); $this->__seleniumExecutionContext->initialize(); } public function destroy() { $this->__seleniumExecutionContext->destroy(); } - + + public function setJavascriptLibrary($javascriptLibrary) + { + $this->__seleniumExecutionContext->setJavascriptLibrary($javascriptLibrary); + } + function __call($method_name, $args) { if(method_exists($this->__seleniumActions, $method_name)) { call_user_func_array( array($this->__seleniumActions, $method_name), $args); return $this; } else if(method_exists(SeleniumExpectations, $method_name)) { call_user_func_array( array($this->__seleniumExpectations, $method_name), $args); return $this; } else { throw new Exception('Unknown method '.$method_name."called on ".get_class($this)." instance."); } } } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExecutionContext.php b/src/selenium_helper/SeleniumExecutionContext.php index 8e92ae1..628c79d 100644 --- a/src/selenium_helper/SeleniumExecutionContext.php +++ b/src/selenium_helper/SeleniumExecutionContext.php @@ -1,84 +1,89 @@ <?php require_once 'src/selenium_helper/SeleniumExtendedDriver.php'; class SeleniumExecutionContext { private $__browser; private $__website; private $__selenium; private $__isInitialized; private $__lastVisitedLocation; private $__javascript_library; public function __construct($browser, $website, $javascript_library) { $this->__browser = $browser; $this->__website = $website; $this->__javascript_library = $javascript_library; $this->__selenium = new SeleniumExtendedDriver($browser, $website); $this->__isInitialized = false; $this->resetLastVisitedLocation(); } public function getBrowser() { return $this->__browser; } public function getWebSite() { return $this->__website; } public function getJavascriptLibrary() { return $this->__javascript_library; } + + public function setJavascriptLibrary($javascriptLibrary) + { + $this->__javascript_library = $javascriptLibrary; + } public function getSelenium() { return $this->__selenium; } public function setLastVisitedLocation($location) { $this->__lastVisitedLocation = $location; } public function getLastVisitedLocation() { return $this->__lastVisitedLocation; } public function resetLastVisitedLocation() { $this->__lastVisitedLocation = null; } public function initialize() { if(!$this->__isInitialized) $this->__startSelenium(); } public function destroy() { if($this->__isInitialized) $this->__stopSelenium(); } private function __startSelenium() { $this->__selenium->start(); $this->__isInitialized = true; } private function __stopSelenium() { $this->__selenium->close(); $this->__selenium->stop(); } } ?> \ No newline at end of file
xto/SUTA
af52dec0210206e67cc819ce15e59244102c6e8c
Added waitforAjax with jQuery... need tests for Ajax with prototype
diff --git a/configuration/Configuration.php b/configuration/Configuration.php index 254640e..95f77f9 100644 --- a/configuration/Configuration.php +++ b/configuration/Configuration.php @@ -1,11 +1,11 @@ <?php class Configuration { - private $SUTA_path = "/home/frank/projects/SUTA/"; - private $selenium_test_page_path = "expectations/selenium_expectations/selenium_test_page.html"; - - public function getSeleniumTestPagePath() + private $SUTA_path = "/home/smpdev/SUTA/"; + private $selenium_test_page_path = "expectations/selenium_expectations/selenium_test_page.html"; + + public function getSeleniumTestPagePath() { - return $this->SUTA_path.$this->selenium_test_page_path; + return $this->SUTA_path.$this->selenium_test_page_path; } } ?> \ No newline at end of file diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php index a45f70e..654357c 100644 --- a/expectations/ExpectationsExpectations.php +++ b/expectations/ExpectationsExpectations.php @@ -1,253 +1,288 @@ <?php require_once 'src/Expectations.php'; - + class ExpectationsExpectations extends PHPUnit_Framework_TestCase { /** * @test */ public function ShouldBeTrueShouldBehaveJustLikeassertTrue() { Expectations::shouldBeTrue(true); self::assertTrue(true); try { self::assertTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeFalseShouldBehaveJustLikeassertFalse() { Expectations::shouldBeFalse(false); self::assertFalse(false); try { self::assertFalse(True); throw new Exception("assertFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeFalse(true); throw new Exception("shouldBeFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldEqualShouldBehaveLikeAssertEqual() { self::assertEquals("tom","tom"); Expectations::shouldEqual("tom","tom"); try { self::assertEquals("foo", "bar"); throw new Exception("assertEquals should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldEqual("foo", "bar"); throw new Exception("shouldEqual should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotBeEqualShouldBehaveLikeAssertNotEquals() { self::assertNotEquals(1,2); Expectations::shouldNotEqual(1,2); try { self::assertNotEquals(1,1); throw new Exception("assertNotEquals should fail when both elements are equal"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotEqual(1,1); throw new Expection("shouldNotEqual should fail when both elements are equal"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeNullShouldBehaveLikeAssertNull() { Expectations::shouldBeNull(null); self::assertNull(null); try { self::assertNull("Something that isn't null"); throw new Exception("assertNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeNull("Something that isn't null"); throw new Exception("shouldBeNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotBeNullShouldBehaveLikeAssertNotNull() { self::assertNotNull("Something not null"); Expectations::shouldNotBeNull("Something not null"); try { self::assertNotNull(null); throw new Exception("assertNotNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotBeNull(null); throw new Exception("shoulNotdBeNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldContainShouldBehaveLikeAssertContains() { self::assertContains("tom","tom petty"); Expectations::shouldContain("tom", "tom petty"); try { self::assertContains("tom", "petty"); throw new Exception("assertContains should fail if the pattern is not in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldContain("tom", "petty"); throw new Exception("shoulContain should fail if the pattern is not in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotContainShouldBehaveLikeAssertNotContains() { self::assertNotContains("tom", "something else"); Expectations::shouldNotContain("tom", "something else"); try { self::assertNotContains("tom", "tom"); throw new Exception("assertNotContains should fail if the pattern is in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotContain("tom", "tom"); throw new Exception("shoulNotContain should fail if the pattern is in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } - + /** * @test */ public function ShouldRaiseExceptionShouldPassWhenExceptationRaisedMatchsExpectedException() { $expected = new Exception("patate"); $actual = $expected; Expectations::shouldRaiseException($actual, $expected); } - - + + /** * @test */ public function ShouldRaiseExceptionShouldFailWhenExceptationRaisedDoesNotMatchExpectedException() { $expected = new Exception("potato"); $actual = new ErrorException("potato"); try { Expectations::shouldRaiseException($actual, $expected); throw new Exception("shouldRaiseException() Should Fail When Exceptation Raised Does Not Match Expected Exception"); }catch (PHPUnit_Framework_ExpectationFailedException $e) { } - + + } + + /** + * @test + */ + public function ShouldEqualShouldPassWhenTheTwoObjectsAreExactlyTheSame() + { + $Nick = new DummyUser("Nick",true); + $Xavier = new DummyUser("Xavier", false); + $Francis = new DummyUser("Francis", true); + + $expected = array($Nick, $Xavier, $Francis); + $actual = array($Nick,$Xavier,$Francis); + + Expectations::shouldEqual($actual,$expected); + } + + /** + * @test + */ + public function ShouldEqualShouldFailWhenTheTwoObjectsAreNotExactlyTheSame() + { + $Nick = new DummyUser("Nick",true); + $Xavier = new DummyUser("Xavier", false); + $Francis = new DummyUser("Francis", true); + + $expected = array($Nick, $Xavier, $Francis); + $actual = array($Xavier,$Francis); + + try{ + Expectations::shouldEqual($actual,$expected); + throw new Expection("shouldNotEqual should fail when both elements are equal"); + } + catch(PHPUnit_Framework_ExpectationFailedException $e) + {} } - - - + + + } ?> \ No newline at end of file diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php index 4208832..1298c5c 100644 --- a/expectations/ExpectationsSuite.php +++ b/expectations/ExpectationsSuite.php @@ -1,41 +1,43 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; require_once 'expectations/ExpectationsExpectations.php'; require_once 'expectations/TestSubjectExpectations.php'; - require_once 'selenium_expectations/SeleniumDrivenUserExpectations.php'; + require_once 'expectations/selenium_expectations/SeleniumDrivenUserExpectations.php'; + require_once 'expectations/selenium_expectations/SeleniumActionsExpectations.php'; class ExpectationsSuite { public static function suite() { $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); $suite->addTestSuite('ExpectationsExpectations'); $suite->addTestSuite('TestSubjectExpectations'); - $suite->addTestSuite('SeleniumDrivenUserExpectations'); + $suite->addTestSuite('SeleniumActionsExpectations'); + //$suite->addTestSuite('SeleniumDrivenUserExpectations'); return $suite; } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumActionsExpectations.php b/expectations/selenium_expectations/SeleniumActionsExpectations.php new file mode 100644 index 0000000..4265a8a --- /dev/null +++ b/expectations/selenium_expectations/SeleniumActionsExpectations.php @@ -0,0 +1,55 @@ +<?php + require_once 'PHPUnit/Framework.php'; + + require_once 'src/selenium_helper/SeleniumExecutionContext.php'; + require_once 'src/selenium_helper/SeleniumActions.php'; + require_once 'src/Expectations.php'; + + class SeleniumActionsExpectations extends PHPUnit_Framework_TestCase + { + public function setUp() + { + $browser = 'firefox'; + $url = 'http://some.url'; + $timeout = 10000; + } + + /** + * @test + */ + public function waitsForAjaxShouldCallWaitForConditionWithjQueryConditionWhenjQueryIsTheLibrary() + { + $mock_seleniumExecutionContext = $this->getMock('SeleniumExecutionContext',array('getSelenium'),array($browser, $url, 'jQuery')); + $mock_selenium = $this->getMock('SeleniumExtendedDriver',array(),array($browser, $url)); + + $mock_seleniumExecutionContext->expects($this->any())->method('getSelenium') + ->will($this->returnValue($mock_selenium)); + + $seleniumActions = new SeleniumActions($mock_seleniumExecutionContext); + + $mock_selenium->expects($this->once())->method('waitForCondition') + ->with("selenium.browserbot.getCurrentWindow().jQuery.active == 0"); + + $seleniumActions->waitsForAjax($timeout); + } + + /** + * @test + */ + public function waitsForAjaxShouldCallWaitForConditionWithPrototypeConditionWhenPrototypeIsTheLibrary() + { + $mock_seleniumExecutionContext = $this->getMock('SeleniumExecutionContext',array('getSelenium'),array($browser, $url, 'Prototype')); + $mock_selenium = $this->getMock('SeleniumExtendedDriver',array(),array($browser, $url)); + + $mock_seleniumExecutionContext->expects($this->any())->method('getSelenium') + ->will($this->returnValue($mock_selenium)); + + $seleniumActions = new SeleniumActions($mock_seleniumExecutionContext); + + $mock_selenium->expects($this->once())->method('waitForCondition') + ->with("selenium.browserbot.getCurrentWindow().Ajax.activeRequestCount == 0"); + + $seleniumActions->waitsForAjax($timeout); + } + } +?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php index d44ccc3..9593b70 100644 --- a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -1,193 +1,205 @@ <?php require_once 'src/selenium_helper/SeleniumDrivenUser.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; require_once 'configuration/Configuration.php'; class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase { private static $selenium_execution_context; private static $selenium_driven_user; private static $selenium_test_page_path; public static function setUpBeforeClass() { $configuration = new Configuration(); - self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); + self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); - self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file://".self::$selenium_test_page_path); + self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file://".self::$selenium_test_page_path, "jQuery"); self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); } public static function tearDownAfterClass() { - self::$selenium_driven_user->destroy(); + self::$selenium_driven_user->destroy(); } public function setUp() { self::$selenium_driven_user->goesTo("file://".self::$selenium_test_page_path); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } /** * @test */ public function shouldNotSeeShouldSucceedWhenElementIsNotFound() { self::$selenium_driven_user->shouldNotSee("//*[id('id_that_dont_exist')]"); } /** * @test */ public function shouldNotSeeShouldFailWhenElementIsFound() { try { self::$selenium_driven_user->shouldNotSee("//*[id('test_span')]"); self::fail("shouldNotSee should have failed"); } catch (Exception $e) { } } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_radio']"); self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_driven_user->selects("Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_driven_user->selects("Option 2")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } + + /** + * @test + */ + public function waitsForAjaxShouldWaitForAjaxRequestToEndBeforeContinuing() + { + $timeout = 5000; + + self::$selenium_driven_user->clicks("//a[id('test_jQuery_link')]") + ->and_then()->waitsForAjax($timeout); + + } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/jquery-1.4.2.min.js b/expectations/selenium_expectations/jquery-1.4.2.min.js new file mode 100644 index 0000000..7c24308 --- /dev/null +++ b/expectations/selenium_expectations/jquery-1.4.2.min.js @@ -0,0 +1,154 @@ +/*! + * jQuery JavaScript Library v1.4.2 + * http://jquery.com/ + * + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2010, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Sat Feb 13 22:33:48 2010 -0500 + */ +(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i? +e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r= +j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g, +"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e= +true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/, +Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&& +(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this, +a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b=== +"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this, +function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)|| +c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded", +L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype, +"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+ +a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f], +d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]=== +a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&& +!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari= +true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; +var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, +parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= +false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= +s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, +applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; +else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, +a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== +w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, +cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ", +i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ", +" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className= +this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i= +e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= +c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); +a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, +function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); +k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), +C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!= +null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type= +e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& +f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; +if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), +fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| +d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this, +"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent= +a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y, +isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit= +{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}}; +if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", +e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, +"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, +d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&& +!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}}, +toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector, +u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "), +function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q]; +if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, +e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); +t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| +g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[]; +for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length- +1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, +CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}}, +relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]= +l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[]; +h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, +CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, +g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, +text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, +setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= +h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m= +m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== +"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, +h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition|| +!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m= +h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& +q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>"; +if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); +(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: +function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/, +gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; +c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= +{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== +"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", +d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? +a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== +1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)? +a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= +c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, +wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, +prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, +this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); +return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, +""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& +this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]|| +u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length=== +1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); +return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", +""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= +c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? +c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= +function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= +Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, +"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= +a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= +a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== +"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, +serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), +function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, +global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& +e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? +"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== +false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= +false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", +c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| +d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); +g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== +1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== +"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; +if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay"); +this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a], +"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)}, +animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing= +j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]); +this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== +"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| +c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; +this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= +this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, +e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length|| +c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement? +function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b= +this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle; +k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&& +f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; +a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); +c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, +d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- +f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": +"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in +e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window); diff --git a/expectations/selenium_expectations/jquery.sleep.js b/expectations/selenium_expectations/jquery.sleep.js new file mode 100644 index 0000000..cb1cc02 --- /dev/null +++ b/expectations/selenium_expectations/jquery.sleep.js @@ -0,0 +1,31 @@ +/* + Sleep by Mark Hughes + http://www.360Gamer.net/ + + Usage: + jQuery.sleep ( 3, function() + { alert ( "I slept for 3 seconds!" ); + }); + Use at free will, distribute free of charge +*/ +;(function(jQuery) +{ var _sleeptimer; + jQuery.sleep = function( time2sleep, callback ) + { jQuery.sleep._sleeptimer = time2sleep; + jQuery.sleep._cback = callback; jQuery.sleep.timer = setInterval('jQuery.sleep.count()', 1000); + } + jQuery.extend (jQuery.sleep, { current_i : 1, + _sleeptimer : 0, + _cback : null, + timer : null, + count : function() + { + if ( jQuery.sleep.current_i === jQuery.sleep._sleeptimer ) + { + clearInterval(jQuery.sleep.timer); + jQuery.sleep._cback.call(this); + } + jQuery.sleep.current_i++; + } + }); +})(jQuery); \ No newline at end of file diff --git a/expectations/selenium_expectations/prototype.js b/expectations/selenium_expectations/prototype.js new file mode 100644 index 0000000..9fe6e12 --- /dev/null +++ b/expectations/selenium_expectations/prototype.js @@ -0,0 +1,4874 @@ +/* Prototype JavaScript framework, version 1.6.1 + * (c) 2005-2009 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://www.prototypejs.org/ + * + *--------------------------------------------------------------------------*/ + +var Prototype = { + Version: '1.6.1', + + Browser: (function(){ + var ua = navigator.userAgent; + var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; + return { + IE: !!window.attachEvent && !isOpera, + Opera: isOpera, + WebKit: ua.indexOf('AppleWebKit/') > -1, + Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1, + MobileSafari: /Apple.*Mobile.*Safari/.test(ua) + } + })(), + + BrowserFeatures: { + XPath: !!document.evaluate, + SelectorsAPI: !!document.querySelector, + ElementExtensions: (function() { + var constructor = window.Element || window.HTMLElement; + return !!(constructor && constructor.prototype); + })(), + SpecificElementExtensions: (function() { + if (typeof window.HTMLDivElement !== 'undefined') + return true; + + var div = document.createElement('div'); + var form = document.createElement('form'); + var isSupported = false; + + if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) { + isSupported = true; + } + + div = form = null; + + return isSupported; + })() + }, + + ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>', + JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, + + emptyFunction: function() { }, + K: function(x) { return x } +}; + +if (Prototype.Browser.MobileSafari) + Prototype.BrowserFeatures.SpecificElementExtensions = false; + + +var Abstract = { }; + + +var Try = { + these: function() { + var returnValue; + + for (var i = 0, length = arguments.length; i < length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) { } + } + + return returnValue; + } +}; + +/* Based on Alex Arnell's inheritance implementation. */ + +var Class = (function() { + function subclass() {}; + function create() { + var parent = null, properties = $A(arguments); + if (Object.isFunction(properties[0])) + parent = properties.shift(); + + function klass() { + this.initialize.apply(this, arguments); + } + + Object.extend(klass, Class.Methods); + klass.superclass = parent; + klass.subclasses = []; + + if (parent) { + subclass.prototype = parent.prototype; + klass.prototype = new subclass; + parent.subclasses.push(klass); + } + + for (var i = 0; i < properties.length; i++) + klass.addMethods(properties[i]); + + if (!klass.prototype.initialize) + klass.prototype.initialize = Prototype.emptyFunction; + + klass.prototype.constructor = klass; + return klass; + } + + function addMethods(source) { + var ancestor = this.superclass && this.superclass.prototype; + var properties = Object.keys(source); + + if (!Object.keys({ toString: true }).length) { + if (source.toString != Object.prototype.toString) + properties.push("toString"); + if (source.valueOf != Object.prototype.valueOf) + properties.push("valueOf"); + } + + for (var i = 0, length = properties.length; i < length; i++) { + var property = properties[i], value = source[property]; + if (ancestor && Object.isFunction(value) && + value.argumentNames().first() == "$super") { + var method = value; + value = (function(m) { + return function() { return ancestor[m].apply(this, arguments); }; + })(property).wrap(method); + + value.valueOf = method.valueOf.bind(method); + value.toString = method.toString.bind(method); + } + this.prototype[property] = value; + } + + return this; + } + + return { + create: create, + Methods: { + addMethods: addMethods + } + }; +})(); +(function() { + + var _toString = Object.prototype.toString; + + function extend(destination, source) { + for (var property in source) + destination[property] = source[property]; + return destination; + } + + function inspect(object) { + try { + if (isUndefined(object)) return 'undefined'; + if (object === null) return 'null'; + return object.inspect ? object.inspect() : String(object); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } + } + + function toJSON(object) { + var type = typeof object; + switch (type) { + case 'undefined': + case 'function': + case 'unknown': return; + case 'boolean': return object.toString(); + } + + if (object === null) return 'null'; + if (object.toJSON) return object.toJSON(); + if (isElement(object)) return; + + var results = []; + for (var property in object) { + var value = toJSON(object[property]); + if (!isUndefined(value)) + results.push(property.toJSON() + ': ' + value); + } + + return '{' + results.join(', ') + '}'; + } + + function toQueryString(object) { + return $H(object).toQueryString(); + } + + function toHTML(object) { + return object && object.toHTML ? object.toHTML() : String.interpret(object); + } + + function keys(object) { + var results = []; + for (var property in object) + results.push(property); + return results; + } + + function values(object) { + var results = []; + for (var property in object) + results.push(object[property]); + return results; + } + + function clone(object) { + return extend({ }, object); + } + + function isElement(object) { + return !!(object && object.nodeType == 1); + } + + function isArray(object) { + return _toString.call(object) == "[object Array]"; + } + + + function isHash(object) { + return object instanceof Hash; + } + + function isFunction(object) { + return typeof object === "function"; + } + + function isString(object) { + return _toString.call(object) == "[object String]"; + } + + function isNumber(object) { + return _toString.call(object) == "[object Number]"; + } + + function isUndefined(object) { + return typeof object === "undefined"; + } + + extend(Object, { + extend: extend, + inspect: inspect, + toJSON: toJSON, + toQueryString: toQueryString, + toHTML: toHTML, + keys: keys, + values: values, + clone: clone, + isElement: isElement, + isArray: isArray, + isHash: isHash, + isFunction: isFunction, + isString: isString, + isNumber: isNumber, + isUndefined: isUndefined + }); +})(); +Object.extend(Function.prototype, (function() { + var slice = Array.prototype.slice; + + function update(array, args) { + var arrayLength = array.length, length = args.length; + while (length--) array[arrayLength + length] = args[length]; + return array; + } + + function merge(array, args) { + array = slice.call(array, 0); + return update(array, args); + } + + function argumentNames() { + var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1] + .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '') + .replace(/\s+/g, '').split(','); + return names.length == 1 && !names[0] ? [] : names; + } + + function bind(context) { + if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this; + var __method = this, args = slice.call(arguments, 1); + return function() { + var a = merge(args, arguments); + return __method.apply(context, a); + } + } + + function bindAsEventListener(context) { + var __method = this, args = slice.call(arguments, 1); + return function(event) { + var a = update([event || window.event], args); + return __method.apply(context, a); + } + } + + function curry() { + if (!arguments.length) return this; + var __method = this, args = slice.call(arguments, 0); + return function() { + var a = merge(args, arguments); + return __method.apply(this, a); + } + } + + function delay(timeout) { + var __method = this, args = slice.call(arguments, 1); + timeout = timeout * 1000 + return window.setTimeout(function() { + return __method.apply(__method, args); + }, timeout); + } + + function defer() { + var args = update([0.01], arguments); + return this.delay.apply(this, args); + } + + function wrap(wrapper) { + var __method = this; + return function() { + var a = update([__method.bind(this)], arguments); + return wrapper.apply(this, a); + } + } + + function methodize() { + if (this._methodized) return this._methodized; + var __method = this; + return this._methodized = function() { + var a = update([this], arguments); + return __method.apply(null, a); + }; + } + + return { + argumentNames: argumentNames, + bind: bind, + bindAsEventListener: bindAsEventListener, + curry: curry, + delay: delay, + defer: defer, + wrap: wrap, + methodize: methodize + } +})()); + + +Date.prototype.toJSON = function() { + return '"' + this.getUTCFullYear() + '-' + + (this.getUTCMonth() + 1).toPaddedString(2) + '-' + + this.getUTCDate().toPaddedString(2) + 'T' + + this.getUTCHours().toPaddedString(2) + ':' + + this.getUTCMinutes().toPaddedString(2) + ':' + + this.getUTCSeconds().toPaddedString(2) + 'Z"'; +}; + + +RegExp.prototype.match = RegExp.prototype.test; + +RegExp.escape = function(str) { + return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); +}; +var PeriodicalExecuter = Class.create({ + initialize: function(callback, frequency) { + this.callback = callback; + this.frequency = frequency; + this.currentlyExecuting = false; + + this.registerCallback(); + }, + + registerCallback: function() { + this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + execute: function() { + this.callback(this); + }, + + stop: function() { + if (!this.timer) return; + clearInterval(this.timer); + this.timer = null; + }, + + onTimerEvent: function() { + if (!this.currentlyExecuting) { + try { + this.currentlyExecuting = true; + this.execute(); + this.currentlyExecuting = false; + } catch(e) { + this.currentlyExecuting = false; + throw e; + } + } + } +}); +Object.extend(String, { + interpret: function(value) { + return value == null ? '' : String(value); + }, + specialChar: { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '\\': '\\\\' + } +}); + +Object.extend(String.prototype, (function() { + + function prepareReplacement(replacement) { + if (Object.isFunction(replacement)) return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; + } + + function gsub(pattern, replacement) { + var result = '', source = this, match; + replacement = prepareReplacement(replacement); + + if (Object.isString(pattern)) + pattern = RegExp.escape(pattern); + + if (!(pattern.length || pattern.source)) { + replacement = replacement(''); + return replacement + source.split('').join(replacement) + replacement; + } + + while (source.length > 0) { + if (match = source.match(pattern)) { + result += source.slice(0, match.index); + result += String.interpret(replacement(match)); + source = source.slice(match.index + match[0].length); + } else { + result += source, source = ''; + } + } + return result; + } + + function sub(pattern, replacement, count) { + replacement = prepareReplacement(replacement); + count = Object.isUndefined(count) ? 1 : count; + + return this.gsub(pattern, function(match) { + if (--count < 0) return match[0]; + return replacement(match); + }); + } + + function scan(pattern, iterator) { + this.gsub(pattern, iterator); + return String(this); + } + + function truncate(length, truncation) { + length = length || 30; + truncation = Object.isUndefined(truncation) ? '...' : truncation; + return this.length > length ? + this.slice(0, length - truncation.length) + truncation : String(this); + } + + function strip() { + return this.replace(/^\s+/, '').replace(/\s+$/, ''); + } + + function stripTags() { + return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ''); + } + + function stripScripts() { + return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); + } + + function extractScripts() { + var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); + var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); + return (this.match(matchAll) || []).map(function(scriptTag) { + return (scriptTag.match(matchOne) || ['', ''])[1]; + }); + } + + function evalScripts() { + return this.extractScripts().map(function(script) { return eval(script) }); + } + + function escapeHTML() { + return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); + } + + function unescapeHTML() { + return this.stripTags().replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&'); + } + + + function toQueryParams(separator) { + var match = this.strip().match(/([^?#]*)(#.*)?$/); + if (!match) return { }; + + return match[1].split(separator || '&').inject({ }, function(hash, pair) { + if ((pair = pair.split('='))[0]) { + var key = decodeURIComponent(pair.shift()); + var value = pair.length > 1 ? pair.join('=') : pair[0]; + if (value != undefined) value = decodeURIComponent(value); + + if (key in hash) { + if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; + hash[key].push(value); + } + else hash[key] = value; + } + return hash; + }); + } + + function toArray() { + return this.split(''); + } + + function succ() { + return this.slice(0, this.length - 1) + + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); + } + + function times(count) { + return count < 1 ? '' : new Array(count + 1).join(this); + } + + function camelize() { + var parts = this.split('-'), len = parts.length; + if (len == 1) return parts[0]; + + var camelized = this.charAt(0) == '-' + ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) + : parts[0]; + + for (var i = 1; i < len; i++) + camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); + + return camelized; + } + + function capitalize() { + return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); + } + + function underscore() { + return this.replace(/::/g, '/') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') + .replace(/([a-z\d])([A-Z])/g, '$1_$2') + .replace(/-/g, '_') + .toLowerCase(); + } + + function dasherize() { + return this.replace(/_/g, '-'); + } + + function inspect(useDoubleQuotes) { + var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) { + if (character in String.specialChar) { + return String.specialChar[character]; + } + return '\\u00' + character.charCodeAt().toPaddedString(2, 16); + }); + if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; + return "'" + escapedString.replace(/'/g, '\\\'') + "'"; + } + + function toJSON() { + return this.inspect(true); + } + + function unfilterJSON(filter) { + return this.replace(filter || Prototype.JSONFilter, '$1'); + } + + function isJSON() { + var str = this; + if (str.blank()) return false; + str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); + return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); + } + + function evalJSON(sanitize) { + var json = this.unfilterJSON(); + try { + if (!sanitize || json.isJSON()) return eval('(' + json + ')'); + } catch (e) { } + throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); + } + + function include(pattern) { + return this.indexOf(pattern) > -1; + } + + function startsWith(pattern) { + return this.indexOf(pattern) === 0; + } + + function endsWith(pattern) { + var d = this.length - pattern.length; + return d >= 0 && this.lastIndexOf(pattern) === d; + } + + function empty() { + return this == ''; + } + + function blank() { + return /^\s*$/.test(this); + } + + function interpolate(object, pattern) { + return new Template(this, pattern).evaluate(object); + } + + return { + gsub: gsub, + sub: sub, + scan: scan, + truncate: truncate, + strip: String.prototype.trim ? String.prototype.trim : strip, + stripTags: stripTags, + stripScripts: stripScripts, + extractScripts: extractScripts, + evalScripts: evalScripts, + escapeHTML: escapeHTML, + unescapeHTML: unescapeHTML, + toQueryParams: toQueryParams, + parseQuery: toQueryParams, + toArray: toArray, + succ: succ, + times: times, + camelize: camelize, + capitalize: capitalize, + underscore: underscore, + dasherize: dasherize, + inspect: inspect, + toJSON: toJSON, + unfilterJSON: unfilterJSON, + isJSON: isJSON, + evalJSON: evalJSON, + include: include, + startsWith: startsWith, + endsWith: endsWith, + empty: empty, + blank: blank, + interpolate: interpolate + }; +})()); + +var Template = Class.create({ + initialize: function(template, pattern) { + this.template = template.toString(); + this.pattern = pattern || Template.Pattern; + }, + + evaluate: function(object) { + if (object && Object.isFunction(object.toTemplateReplacements)) + object = object.toTemplateReplacements(); + + return this.template.gsub(this.pattern, function(match) { + if (object == null) return (match[1] + ''); + + var before = match[1] || ''; + if (before == '\\') return match[2]; + + var ctx = object, expr = match[3]; + var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/; + match = pattern.exec(expr); + if (match == null) return before; + + while (match != null) { + var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1]; + ctx = ctx[comp]; + if (null == ctx || '' == match[3]) break; + expr = expr.substring('[' == match[3] ? match[1].length : match[0].length); + match = pattern.exec(expr); + } + + return before + String.interpret(ctx); + }); + } +}); +Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; + +var $break = { }; + +var Enumerable = (function() { + function each(iterator, context) { + var index = 0; + try { + this._each(function(value) { + iterator.call(context, value, index++); + }); + } catch (e) { + if (e != $break) throw e; + } + return this; + } + + function eachSlice(number, iterator, context) { + var index = -number, slices = [], array = this.toArray(); + if (number < 1) return array; + while ((index += number) < array.length) + slices.push(array.slice(index, index+number)); + return slices.collect(iterator, context); + } + + function all(iterator, context) { + iterator = iterator || Prototype.K; + var result = true; + this.each(function(value, index) { + result = result && !!iterator.call(context, value, index); + if (!result) throw $break; + }); + return result; + } + + function any(iterator, context) { + iterator = iterator || Prototype.K; + var result = false; + this.each(function(value, index) { + if (result = !!iterator.call(context, value, index)) + throw $break; + }); + return result; + } + + function collect(iterator, context) { + iterator = iterator || Prototype.K; + var results = []; + this.each(function(value, index) { + results.push(iterator.call(context, value, index)); + }); + return results; + } + + function detect(iterator, context) { + var result; + this.each(function(value, index) { + if (iterator.call(context, value, index)) { + result = value; + throw $break; + } + }); + return result; + } + + function findAll(iterator, context) { + var results = []; + this.each(function(value, index) { + if (iterator.call(context, value, index)) + results.push(value); + }); + return results; + } + + function grep(filter, iterator, context) { + iterator = iterator || Prototype.K; + var results = []; + + if (Object.isString(filter)) + filter = new RegExp(RegExp.escape(filter)); + + this.each(function(value, index) { + if (filter.match(value)) + results.push(iterator.call(context, value, index)); + }); + return results; + } + + function include(object) { + if (Object.isFunction(this.indexOf)) + if (this.indexOf(object) != -1) return true; + + var found = false; + this.each(function(value) { + if (value == object) { + found = true; + throw $break; + } + }); + return found; + } + + function inGroupsOf(number, fillWith) { + fillWith = Object.isUndefined(fillWith) ? null : fillWith; + return this.eachSlice(number, function(slice) { + while(slice.length < number) slice.push(fillWith); + return slice; + }); + } + + function inject(memo, iterator, context) { + this.each(function(value, index) { + memo = iterator.call(context, memo, value, index); + }); + return memo; + } + + function invoke(method) { + var args = $A(arguments).slice(1); + return this.map(function(value) { + return value[method].apply(value, args); + }); + } + + function max(iterator, context) { + iterator = iterator || Prototype.K; + var result; + this.each(function(value, index) { + value = iterator.call(context, value, index); + if (result == null || value >= result) + result = value; + }); + return result; + } + + function min(iterator, context) { + iterator = iterator || Prototype.K; + var result; + this.each(function(value, index) { + value = iterator.call(context, value, index); + if (result == null || value < result) + result = value; + }); + return result; + } + + function partition(iterator, context) { + iterator = iterator || Prototype.K; + var trues = [], falses = []; + this.each(function(value, index) { + (iterator.call(context, value, index) ? + trues : falses).push(value); + }); + return [trues, falses]; + } + + function pluck(property) { + var results = []; + this.each(function(value) { + results.push(value[property]); + }); + return results; + } + + function reject(iterator, context) { + var results = []; + this.each(function(value, index) { + if (!iterator.call(context, value, index)) + results.push(value); + }); + return results; + } + + function sortBy(iterator, context) { + return this.map(function(value, index) { + return { + value: value, + criteria: iterator.call(context, value, index) + }; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }).pluck('value'); + } + + function toArray() { + return this.map(); + } + + function zip() { + var iterator = Prototype.K, args = $A(arguments); + if (Object.isFunction(args.last())) + iterator = args.pop(); + + var collections = [this].concat(args).map($A); + return this.map(function(value, index) { + return iterator(collections.pluck(index)); + }); + } + + function size() { + return this.toArray().length; + } + + function inspect() { + return '#<Enumerable:' + this.toArray().inspect() + '>'; + } + + + + + + + + + + return { + each: each, + eachSlice: eachSlice, + all: all, + every: all, + any: any, + some: any, + collect: collect, + map: collect, + detect: detect, + findAll: findAll, + select: findAll, + filter: findAll, + grep: grep, + include: include, + member: include, + inGroupsOf: inGroupsOf, + inject: inject, + invoke: invoke, + max: max, + min: min, + partition: partition, + pluck: pluck, + reject: reject, + sortBy: sortBy, + toArray: toArray, + entries: toArray, + zip: zip, + size: size, + inspect: inspect, + find: detect + }; +})(); +function $A(iterable) { + if (!iterable) return []; + if ('toArray' in Object(iterable)) return iterable.toArray(); + var length = iterable.length || 0, results = new Array(length); + while (length--) results[length] = iterable[length]; + return results; +} + +function $w(string) { + if (!Object.isString(string)) return []; + string = string.strip(); + return string ? string.split(/\s+/) : []; +} + +Array.from = $A; + + +(function() { + var arrayProto = Array.prototype, + slice = arrayProto.slice, + _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available + + function each(iterator) { + for (var i = 0, length = this.length; i < length; i++) + iterator(this[i]); + } + if (!_each) _each = each; + + function clear() { + this.length = 0; + return this; + } + + function first() { + return this[0]; + } + + function last() { + return this[this.length - 1]; + } + + function compact() { + return this.select(function(value) { + return value != null; + }); + } + + function flatten() { + return this.inject([], function(array, value) { + if (Object.isArray(value)) + return array.concat(value.flatten()); + array.push(value); + return array; + }); + } + + function without() { + var values = slice.call(arguments, 0); + return this.select(function(value) { + return !values.include(value); + }); + } + + function reverse(inline) { + return (inline !== false ? this : this.toArray())._reverse(); + } + + function uniq(sorted) { + return this.inject([], function(array, value, index) { + if (0 == index || (sorted ? array.last() != value : !array.include(value))) + array.push(value); + return array; + }); + } + + function intersect(array) { + return this.uniq().findAll(function(item) { + return array.detect(function(value) { return item === value }); + }); + } + + + function clone() { + return slice.call(this, 0); + } + + function size() { + return this.length; + } + + function inspect() { + return '[' + this.map(Object.inspect).join(', ') + ']'; + } + + function toJSON() { + var results = []; + this.each(function(object) { + var value = Object.toJSON(object); + if (!Object.isUndefined(value)) results.push(value); + }); + return '[' + results.join(', ') + ']'; + } + + function indexOf(item, i) { + i || (i = 0); + var length = this.length; + if (i < 0) i = length + i; + for (; i < length; i++) + if (this[i] === item) return i; + return -1; + } + + function lastIndexOf(item, i) { + i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1; + var n = this.slice(0, i).reverse().indexOf(item); + return (n < 0) ? n : i - n - 1; + } + + function concat() { + var array = slice.call(this, 0), item; + for (var i = 0, length = arguments.length; i < length; i++) { + item = arguments[i]; + if (Object.isArray(item) && !('callee' in item)) { + for (var j = 0, arrayLength = item.length; j < arrayLength; j++) + array.push(item[j]); + } else { + array.push(item); + } + } + return array; + } + + Object.extend(arrayProto, Enumerable); + + if (!arrayProto._reverse) + arrayProto._reverse = arrayProto.reverse; + + Object.extend(arrayProto, { + _each: _each, + clear: clear, + first: first, + last: last, + compact: compact, + flatten: flatten, + without: without, + reverse: reverse, + uniq: uniq, + intersect: intersect, + clone: clone, + toArray: clone, + size: size, + inspect: inspect, + toJSON: toJSON + }); + + var CONCAT_ARGUMENTS_BUGGY = (function() { + return [].concat(arguments)[0][0] !== 1; + })(1,2) + + if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat; + + if (!arrayProto.indexOf) arrayProto.indexOf = indexOf; + if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf; +})(); +function $H(object) { + return new Hash(object); +}; + +var Hash = Class.create(Enumerable, (function() { + function initialize(object) { + this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); + } + + function _each(iterator) { + for (var key in this._object) { + var value = this._object[key], pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + } + + function set(key, value) { + return this._object[key] = value; + } + + function get(key) { + if (this._object[key] !== Object.prototype[key]) + return this._object[key]; + } + + function unset(key) { + var value = this._object[key]; + delete this._object[key]; + return value; + } + + function toObject() { + return Object.clone(this._object); + } + + function keys() { + return this.pluck('key'); + } + + function values() { + return this.pluck('value'); + } + + function index(value) { + var match = this.detect(function(pair) { + return pair.value === value; + }); + return match && match.key; + } + + function merge(object) { + return this.clone().update(object); + } + + function update(object) { + return new Hash(object).inject(this, function(result, pair) { + result.set(pair.key, pair.value); + return result; + }); + } + + function toQueryPair(key, value) { + if (Object.isUndefined(value)) return key; + return key + '=' + encodeURIComponent(String.interpret(value)); + } + + function toQueryString() { + return this.inject([], function(results, pair) { + var key = encodeURIComponent(pair.key), values = pair.value; + + if (values && typeof values == 'object') { + if (Object.isArray(values)) + return results.concat(values.map(toQueryPair.curry(key))); + } else results.push(toQueryPair(key, values)); + return results; + }).join('&'); + } + + function inspect() { + return '#<Hash:{' + this.map(function(pair) { + return pair.map(Object.inspect).join(': '); + }).join(', ') + '}>'; + } + + function toJSON() { + return Object.toJSON(this.toObject()); + } + + function clone() { + return new Hash(this); + } + + return { + initialize: initialize, + _each: _each, + set: set, + get: get, + unset: unset, + toObject: toObject, + toTemplateReplacements: toObject, + keys: keys, + values: values, + index: index, + merge: merge, + update: update, + toQueryString: toQueryString, + inspect: inspect, + toJSON: toJSON, + clone: clone + }; +})()); + +Hash.from = $H; +Object.extend(Number.prototype, (function() { + function toColorPart() { + return this.toPaddedString(2, 16); + } + + function succ() { + return this + 1; + } + + function times(iterator, context) { + $R(0, this, true).each(iterator, context); + return this; + } + + function toPaddedString(length, radix) { + var string = this.toString(radix || 10); + return '0'.times(length - string.length) + string; + } + + function toJSON() { + return isFinite(this) ? this.toString() : 'null'; + } + + function abs() { + return Math.abs(this); + } + + function round() { + return Math.round(this); + } + + function ceil() { + return Math.ceil(this); + } + + function floor() { + return Math.floor(this); + } + + return { + toColorPart: toColorPart, + succ: succ, + times: times, + toPaddedString: toPaddedString, + toJSON: toJSON, + abs: abs, + round: round, + ceil: ceil, + floor: floor + }; +})()); + +function $R(start, end, exclusive) { + return new ObjectRange(start, end, exclusive); +} + +var ObjectRange = Class.create(Enumerable, (function() { + function initialize(start, end, exclusive) { + this.start = start; + this.end = end; + this.exclusive = exclusive; + } + + function _each(iterator) { + var value = this.start; + while (this.include(value)) { + iterator(value); + value = value.succ(); + } + } + + function include(value) { + if (value < this.start) + return false; + if (this.exclusive) + return value < this.end; + return value <= this.end; + } + + return { + initialize: initialize, + _each: _each, + include: include + }; +})()); + + + +var Ajax = { + getTransport: function() { + return Try.these( + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject('Msxml2.XMLHTTP')}, + function() {return new ActiveXObject('Microsoft.XMLHTTP')} + ) || false; + }, + + activeRequestCount: 0 +}; + +Ajax.Responders = { + responders: [], + + _each: function(iterator) { + this.responders._each(iterator); + }, + + register: function(responder) { + if (!this.include(responder)) + this.responders.push(responder); + }, + + unregister: function(responder) { + this.responders = this.responders.without(responder); + }, + + dispatch: function(callback, request, transport, json) { + this.each(function(responder) { + if (Object.isFunction(responder[callback])) { + try { + responder[callback].apply(responder, [request, transport, json]); + } catch (e) { } + } + }); + } +}; + +Object.extend(Ajax.Responders, Enumerable); + +Ajax.Responders.register({ + onCreate: function() { Ajax.activeRequestCount++ }, + onComplete: function() { Ajax.activeRequestCount-- } +}); +Ajax.Base = Class.create({ + initialize: function(options) { + this.options = { + method: 'post', + asynchronous: true, + contentType: 'application/x-www-form-urlencoded', + encoding: 'UTF-8', + parameters: '', + evalJSON: true, + evalJS: true + }; + Object.extend(this.options, options || { }); + + this.options.method = this.options.method.toLowerCase(); + + if (Object.isString(this.options.parameters)) + this.options.parameters = this.options.parameters.toQueryParams(); + else if (Object.isHash(this.options.parameters)) + this.options.parameters = this.options.parameters.toObject(); + } +}); +Ajax.Request = Class.create(Ajax.Base, { + _complete: false, + + initialize: function($super, url, options) { + $super(options); + this.transport = Ajax.getTransport(); + this.request(url); + }, + + request: function(url) { + this.url = url; + this.method = this.options.method; + var params = Object.clone(this.options.parameters); + + if (!['get', 'post'].include(this.method)) { + params['_method'] = this.method; + this.method = 'post'; + } + + this.parameters = params; + + if (params = Object.toQueryString(params)) { + if (this.method == 'get') + this.url += (this.url.include('?') ? '&' : '?') + params; + else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) + params += '&_='; + } + + try { + var response = new Ajax.Response(this); + if (this.options.onCreate) this.options.onCreate(response); + Ajax.Responders.dispatch('onCreate', this, response); + + this.transport.open(this.method.toUpperCase(), this.url, + this.options.asynchronous); + + if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1); + + this.transport.onreadystatechange = this.onStateChange.bind(this); + this.setRequestHeaders(); + + this.body = this.method == 'post' ? (this.options.postBody || params) : null; + this.transport.send(this.body); + + /* Force Firefox to handle ready state 4 for synchronous requests */ + if (!this.options.asynchronous && this.transport.overrideMimeType) + this.onStateChange(); + + } + catch (e) { + this.dispatchException(e); + } + }, + + onStateChange: function() { + var readyState = this.transport.readyState; + if (readyState > 1 && !((readyState == 4) && this._complete)) + this.respondToReadyState(this.transport.readyState); + }, + + setRequestHeaders: function() { + var headers = { + 'X-Requested-With': 'XMLHttpRequest', + 'X-Prototype-Version': Prototype.Version, + 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' + }; + + if (this.method == 'post') { + headers['Content-type'] = this.options.contentType + + (this.options.encoding ? '; charset=' + this.options.encoding : ''); + + /* Force "Connection: close" for older Mozilla browsers to work + * around a bug where XMLHttpRequest sends an incorrect + * Content-length header. See Mozilla Bugzilla #246651. + */ + if (this.transport.overrideMimeType && + (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) + headers['Connection'] = 'close'; + } + + if (typeof this.options.requestHeaders == 'object') { + var extras = this.options.requestHeaders; + + if (Object.isFunction(extras.push)) + for (var i = 0, length = extras.length; i < length; i += 2) + headers[extras[i]] = extras[i+1]; + else + $H(extras).each(function(pair) { headers[pair.key] = pair.value }); + } + + for (var name in headers) + this.transport.setRequestHeader(name, headers[name]); + }, + + success: function() { + var status = this.getStatus(); + return !status || (status >= 200 && status < 300); + }, + + getStatus: function() { + try { + return this.transport.status || 0; + } catch (e) { return 0 } + }, + + respondToReadyState: function(readyState) { + var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this); + + if (state == 'Complete') { + try { + this._complete = true; + (this.options['on' + response.status] + || this.options['on' + (this.success() ? 'Success' : 'Failure')] + || Prototype.emptyFunction)(response, response.headerJSON); + } catch (e) { + this.dispatchException(e); + } + + var contentType = response.getHeader('Content-type'); + if (this.options.evalJS == 'force' + || (this.options.evalJS && this.isSameOrigin() && contentType + && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) + this.evalResponse(); + } + + try { + (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON); + Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON); + } catch (e) { + this.dispatchException(e); + } + + if (state == 'Complete') { + this.transport.onreadystatechange = Prototype.emptyFunction; + } + }, + + isSameOrigin: function() { + var m = this.url.match(/^\s*https?:\/\/[^\/]*/); + return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({ + protocol: location.protocol, + domain: document.domain, + port: location.port ? ':' + location.port : '' + })); + }, + + getHeader: function(name) { + try { + return this.transport.getResponseHeader(name) || null; + } catch (e) { return null; } + }, + + evalResponse: function() { + try { + return eval((this.transport.responseText || '').unfilterJSON()); + } catch (e) { + this.dispatchException(e); + } + }, + + dispatchException: function(exception) { + (this.options.onException || Prototype.emptyFunction)(this, exception); + Ajax.Responders.dispatch('onException', this, exception); + } +}); + +Ajax.Request.Events = + ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + + + + + + + + +Ajax.Response = Class.create({ + initialize: function(request){ + this.request = request; + var transport = this.transport = request.transport, + readyState = this.readyState = transport.readyState; + + if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { + this.status = this.getStatus(); + this.statusText = this.getStatusText(); + this.responseText = String.interpret(transport.responseText); + this.headerJSON = this._getHeaderJSON(); + } + + if(readyState == 4) { + var xml = transport.responseXML; + this.responseXML = Object.isUndefined(xml) ? null : xml; + this.responseJSON = this._getResponseJSON(); + } + }, + + status: 0, + + statusText: '', + + getStatus: Ajax.Request.prototype.getStatus, + + getStatusText: function() { + try { + return this.transport.statusText || ''; + } catch (e) { return '' } + }, + + getHeader: Ajax.Request.prototype.getHeader, + + getAllHeaders: function() { + try { + return this.getAllResponseHeaders(); + } catch (e) { return null } + }, + + getResponseHeader: function(name) { + return this.transport.getResponseHeader(name); + }, + + getAllResponseHeaders: function() { + return this.transport.getAllResponseHeaders(); + }, + + _getHeaderJSON: function() { + var json = this.getHeader('X-JSON'); + if (!json) return null; + json = decodeURIComponent(escape(json)); + try { + return json.evalJSON(this.request.options.sanitizeJSON || + !this.request.isSameOrigin()); + } catch (e) { + this.request.dispatchException(e); + } + }, + + _getResponseJSON: function() { + var options = this.request.options; + if (!options.evalJSON || (options.evalJSON != 'force' && + !(this.getHeader('Content-type') || '').include('application/json')) || + this.responseText.blank()) + return null; + try { + return this.responseText.evalJSON(options.sanitizeJSON || + !this.request.isSameOrigin()); + } catch (e) { + this.request.dispatchException(e); + } + } +}); + +Ajax.Updater = Class.create(Ajax.Request, { + initialize: function($super, container, url, options) { + this.container = { + success: (container.success || container), + failure: (container.failure || (container.success ? null : container)) + }; + + options = Object.clone(options); + var onComplete = options.onComplete; + options.onComplete = (function(response, json) { + this.updateContent(response.responseText); + if (Object.isFunction(onComplete)) onComplete(response, json); + }).bind(this); + + $super(url, options); + }, + + updateContent: function(responseText) { + var receiver = this.container[this.success() ? 'success' : 'failure'], + options = this.options; + + if (!options.evalScripts) responseText = responseText.stripScripts(); + + if (receiver = $(receiver)) { + if (options.insertion) { + if (Object.isString(options.insertion)) { + var insertion = { }; insertion[options.insertion] = responseText; + receiver.insert(insertion); + } + else options.insertion(receiver, responseText); + } + else receiver.update(responseText); + } + } +}); + +Ajax.PeriodicalUpdater = Class.create(Ajax.Base, { + initialize: function($super, container, url, options) { + $super(options); + this.onComplete = this.options.onComplete; + + this.frequency = (this.options.frequency || 2); + this.decay = (this.options.decay || 1); + + this.updater = { }; + this.container = container; + this.url = url; + + this.start(); + }, + + start: function() { + this.options.onComplete = this.updateComplete.bind(this); + this.onTimerEvent(); + }, + + stop: function() { + this.updater.options.onComplete = undefined; + clearTimeout(this.timer); + (this.onComplete || Prototype.emptyFunction).apply(this, arguments); + }, + + updateComplete: function(response) { + if (this.options.decay) { + this.decay = (response.responseText == this.lastText ? + this.decay * this.options.decay : 1); + + this.lastText = response.responseText; + } + this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency); + }, + + onTimerEvent: function() { + this.updater = new Ajax.Updater(this.container, this.url, this.options); + } +}); + + + +function $(element) { + if (arguments.length > 1) { + for (var i = 0, elements = [], length = arguments.length; i < length; i++) + elements.push($(arguments[i])); + return elements; + } + if (Object.isString(element)) + element = document.getElementById(element); + return Element.extend(element); +} + +if (Prototype.BrowserFeatures.XPath) { + document._getElementsByXPath = function(expression, parentElement) { + var results = []; + var query = document.evaluate(expression, $(parentElement) || document, + null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (var i = 0, length = query.snapshotLength; i < length; i++) + results.push(Element.extend(query.snapshotItem(i))); + return results; + }; +} + +/*--------------------------------------------------------------------------*/ + +if (!window.Node) var Node = { }; + +if (!Node.ELEMENT_NODE) { + Object.extend(Node, { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }); +} + + +(function(global) { + + var SETATTRIBUTE_IGNORES_NAME = (function(){ + var elForm = document.createElement("form"); + var elInput = document.createElement("input"); + var root = document.documentElement; + elInput.setAttribute("name", "test"); + elForm.appendChild(elInput); + root.appendChild(elForm); + var isBuggy = elForm.elements + ? (typeof elForm.elements.test == "undefined") + : null; + root.removeChild(elForm); + elForm = elInput = null; + return isBuggy; + })(); + + var element = global.Element; + global.Element = function(tagName, attributes) { + attributes = attributes || { }; + tagName = tagName.toLowerCase(); + var cache = Element.cache; + if (SETATTRIBUTE_IGNORES_NAME && attributes.name) { + tagName = '<' + tagName + ' name="' + attributes.name + '">'; + delete attributes.name; + return Element.writeAttribute(document.createElement(tagName), attributes); + } + if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName)); + return Element.writeAttribute(cache[tagName].cloneNode(false), attributes); + }; + Object.extend(global.Element, element || { }); + if (element) global.Element.prototype = element.prototype; +})(this); + +Element.cache = { }; +Element.idCounter = 1; + +Element.Methods = { + visible: function(element) { + return $(element).style.display != 'none'; + }, + + toggle: function(element) { + element = $(element); + Element[Element.visible(element) ? 'hide' : 'show'](element); + return element; + }, + + + hide: function(element) { + element = $(element); + element.style.display = 'none'; + return element; + }, + + show: function(element) { + element = $(element); + element.style.display = ''; + return element; + }, + + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + return element; + }, + + update: (function(){ + + var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){ + var el = document.createElement("select"), + isBuggy = true; + el.innerHTML = "<option value=\"test\">test</option>"; + if (el.options && el.options[0]) { + isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION"; + } + el = null; + return isBuggy; + })(); + + var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){ + try { + var el = document.createElement("table"); + if (el && el.tBodies) { + el.innerHTML = "<tbody><tr><td>test</td></tr></tbody>"; + var isBuggy = typeof el.tBodies[0] == "undefined"; + el = null; + return isBuggy; + } + } catch (e) { + return true; + } + })(); + + var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () { + var s = document.createElement("script"), + isBuggy = false; + try { + s.appendChild(document.createTextNode("")); + isBuggy = !s.firstChild || + s.firstChild && s.firstChild.nodeType !== 3; + } catch (e) { + isBuggy = true; + } + s = null; + return isBuggy; + })(); + + function update(element, content) { + element = $(element); + + if (content && content.toElement) + content = content.toElement(); + + if (Object.isElement(content)) + return element.update().insert(content); + + content = Object.toHTML(content); + + var tagName = element.tagName.toUpperCase(); + + if (tagName === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) { + element.text = content; + return element; + } + + if (SELECT_ELEMENT_INNERHTML_BUGGY || TABLE_ELEMENT_INNERHTML_BUGGY) { + if (tagName in Element._insertionTranslations.tags) { + while (element.firstChild) { + element.removeChild(element.firstChild); + } + Element._getContentFromAnonymousElement(tagName, content.stripScripts()) + .each(function(node) { + element.appendChild(node) + }); + } + else { + element.innerHTML = content.stripScripts(); + } + } + else { + element.innerHTML = content.stripScripts(); + } + + content.evalScripts.bind(content).defer(); + return element; + } + + return update; + })(), + + replace: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + else if (!Object.isElement(content)) { + content = Object.toHTML(content); + var range = element.ownerDocument.createRange(); + range.selectNode(element); + content.evalScripts.bind(content).defer(); + content = range.createContextualFragment(content.stripScripts()); + } + element.parentNode.replaceChild(content, element); + return element; + }, + + insert: function(element, insertions) { + element = $(element); + + if (Object.isString(insertions) || Object.isNumber(insertions) || + Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) + insertions = {bottom:insertions}; + + var content, insert, tagName, childNodes; + + for (var position in insertions) { + content = insertions[position]; + position = position.toLowerCase(); + insert = Element._insertionTranslations[position]; + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + insert(element, content); + continue; + } + + content = Object.toHTML(content); + + tagName = ((position == 'before' || position == 'after') + ? element.parentNode : element).tagName.toUpperCase(); + + childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + + if (position == 'top' || position == 'after') childNodes.reverse(); + childNodes.each(insert.curry(element)); + + content.evalScripts.bind(content).defer(); + } + + return element; + }, + + wrap: function(element, wrapper, attributes) { + element = $(element); + if (Object.isElement(wrapper)) + $(wrapper).writeAttribute(attributes || { }); + else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes); + else wrapper = new Element('div', wrapper); + if (element.parentNode) + element.parentNode.replaceChild(wrapper, element); + wrapper.appendChild(element); + return wrapper; + }, + + inspect: function(element) { + element = $(element); + var result = '<' + element.tagName.toLowerCase(); + $H({'id': 'id', 'className': 'class'}).each(function(pair) { + var property = pair.first(), attribute = pair.last(); + var value = (element[property] || '').toString(); + if (value) result += ' ' + attribute + '=' + value.inspect(true); + }); + return result + '>'; + }, + + recursivelyCollect: function(element, property) { + element = $(element); + var elements = []; + while (element = element[property]) + if (element.nodeType == 1) + elements.push(Element.extend(element)); + return elements; + }, + + ancestors: function(element) { + return Element.recursivelyCollect(element, 'parentNode'); + }, + + descendants: function(element) { + return Element.select(element, "*"); + }, + + firstDescendant: function(element) { + element = $(element).firstChild; + while (element && element.nodeType != 1) element = element.nextSibling; + return $(element); + }, + + immediateDescendants: function(element) { + if (!(element = $(element).firstChild)) return []; + while (element && element.nodeType != 1) element = element.nextSibling; + if (element) return [element].concat($(element).nextSiblings()); + return []; + }, + + previousSiblings: function(element) { + return Element.recursivelyCollect(element, 'previousSibling'); + }, + + nextSiblings: function(element) { + return Element.recursivelyCollect(element, 'nextSibling'); + }, + + siblings: function(element) { + element = $(element); + return Element.previousSiblings(element).reverse() + .concat(Element.nextSiblings(element)); + }, + + match: function(element, selector) { + if (Object.isString(selector)) + selector = new Selector(selector); + return selector.match($(element)); + }, + + up: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(element.parentNode); + var ancestors = Element.ancestors(element); + return Object.isNumber(expression) ? ancestors[expression] : + Selector.findElement(ancestors, expression, index); + }, + + down: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return Element.firstDescendant(element); + return Object.isNumber(expression) ? Element.descendants(element)[expression] : + Element.select(element, expression)[index || 0]; + }, + + previous: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element)); + var previousSiblings = Element.previousSiblings(element); + return Object.isNumber(expression) ? previousSiblings[expression] : + Selector.findElement(previousSiblings, expression, index); + }, + + next: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element)); + var nextSiblings = Element.nextSiblings(element); + return Object.isNumber(expression) ? nextSiblings[expression] : + Selector.findElement(nextSiblings, expression, index); + }, + + + select: function(element) { + var args = Array.prototype.slice.call(arguments, 1); + return Selector.findChildElements(element, args); + }, + + adjacent: function(element) { + var args = Array.prototype.slice.call(arguments, 1); + return Selector.findChildElements(element.parentNode, args).without(element); + }, + + identify: function(element) { + element = $(element); + var id = Element.readAttribute(element, 'id'); + if (id) return id; + do { id = 'anonymous_element_' + Element.idCounter++ } while ($(id)); + Element.writeAttribute(element, 'id', id); + return id; + }, + + readAttribute: function(element, name) { + element = $(element); + if (Prototype.Browser.IE) { + var t = Element._attributeTranslations.read; + if (t.values[name]) return t.values[name](element, name); + if (t.names[name]) name = t.names[name]; + if (name.include(':')) { + return (!element.attributes || !element.attributes[name]) ? null : + element.attributes[name].value; + } + } + return element.getAttribute(name); + }, + + writeAttribute: function(element, name, value) { + element = $(element); + var attributes = { }, t = Element._attributeTranslations.write; + + if (typeof name == 'object') attributes = name; + else attributes[name] = Object.isUndefined(value) ? true : value; + + for (var attr in attributes) { + name = t.names[attr] || attr; + value = attributes[attr]; + if (t.values[attr]) name = t.values[attr](element, value); + if (value === false || value === null) + element.removeAttribute(name); + else if (value === true) + element.setAttribute(name, name); + else element.setAttribute(name, value); + } + return element; + }, + + getHeight: function(element) { + return Element.getDimensions(element).height; + }, + + getWidth: function(element) { + return Element.getDimensions(element).width; + }, + + classNames: function(element) { + return new Element.ClassNames(element); + }, + + hasClassName: function(element, className) { + if (!(element = $(element))) return; + var elementClassName = element.className; + return (elementClassName.length > 0 && (elementClassName == className || + new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); + }, + + addClassName: function(element, className) { + if (!(element = $(element))) return; + if (!Element.hasClassName(element, className)) + element.className += (element.className ? ' ' : '') + className; + return element; + }, + + removeClassName: function(element, className) { + if (!(element = $(element))) return; + element.className = element.className.replace( + new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip(); + return element; + }, + + toggleClassName: function(element, className) { + if (!(element = $(element))) return; + return Element[Element.hasClassName(element, className) ? + 'removeClassName' : 'addClassName'](element, className); + }, + + cleanWhitespace: function(element) { + element = $(element); + var node = element.firstChild; + while (node) { + var nextNode = node.nextSibling; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + element.removeChild(node); + node = nextNode; + } + return element; + }, + + empty: function(element) { + return $(element).innerHTML.blank(); + }, + + descendantOf: function(element, ancestor) { + element = $(element), ancestor = $(ancestor); + + if (element.compareDocumentPosition) + return (element.compareDocumentPosition(ancestor) & 8) === 8; + + if (ancestor.contains) + return ancestor.contains(element) && ancestor !== element; + + while (element = element.parentNode) + if (element == ancestor) return true; + + return false; + }, + + scrollTo: function(element) { + element = $(element); + var pos = Element.cumulativeOffset(element); + window.scrollTo(pos[0], pos[1]); + return element; + }, + + getStyle: function(element, style) { + element = $(element); + style = style == 'float' ? 'cssFloat' : style.camelize(); + var value = element.style[style]; + if (!value || value == 'auto') { + var css = document.defaultView.getComputedStyle(element, null); + value = css ? css[style] : null; + } + if (style == 'opacity') return value ? parseFloat(value) : 1.0; + return value == 'auto' ? null : value; + }, + + getOpacity: function(element) { + return $(element).getStyle('opacity'); + }, + + setStyle: function(element, styles) { + element = $(element); + var elementStyle = element.style, match; + if (Object.isString(styles)) { + element.style.cssText += ';' + styles; + return styles.include('opacity') ? + element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element; + } + for (var property in styles) + if (property == 'opacity') element.setOpacity(styles[property]); + else + elementStyle[(property == 'float' || property == 'cssFloat') ? + (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') : + property] = styles[property]; + + return element; + }, + + setOpacity: function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + return element; + }, + + getDimensions: function(element) { + element = $(element); + var display = Element.getStyle(element, 'display'); + if (display != 'none' && display != null) // Safari bug + return {width: element.offsetWidth, height: element.offsetHeight}; + + var els = element.style; + var originalVisibility = els.visibility; + var originalPosition = els.position; + var originalDisplay = els.display; + els.visibility = 'hidden'; + if (originalPosition != 'fixed') // Switching fixed to absolute causes issues in Safari + els.position = 'absolute'; + els.display = 'block'; + var originalWidth = element.clientWidth; + var originalHeight = element.clientHeight; + els.display = originalDisplay; + els.position = originalPosition; + els.visibility = originalVisibility; + return {width: originalWidth, height: originalHeight}; + }, + + makePositioned: function(element) { + element = $(element); + var pos = Element.getStyle(element, 'position'); + if (pos == 'static' || !pos) { + element._madePositioned = true; + element.style.position = 'relative'; + if (Prototype.Browser.Opera) { + element.style.top = 0; + element.style.left = 0; + } + } + return element; + }, + + undoPositioned: function(element) { + element = $(element); + if (element._madePositioned) { + element._madePositioned = undefined; + element.style.position = + element.style.top = + element.style.left = + element.style.bottom = + element.style.right = ''; + } + return element; + }, + + makeClipping: function(element) { + element = $(element); + if (element._overflow) return element; + element._overflow = Element.getStyle(element, 'overflow') || 'auto'; + if (element._overflow !== 'hidden') + element.style.overflow = 'hidden'; + return element; + }, + + undoClipping: function(element) { + element = $(element); + if (!element._overflow) return element; + element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; + element._overflow = null; + return element; + }, + + cumulativeOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + positionedOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + if (element) { + if (element.tagName.toUpperCase() == 'BODY') break; + var p = Element.getStyle(element, 'position'); + if (p !== 'static') break; + } + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + absolutize: function(element) { + element = $(element); + if (Element.getStyle(element, 'position') == 'absolute') return element; + + var offsets = Element.positionedOffset(element); + var top = offsets[1]; + var left = offsets[0]; + var width = element.clientWidth; + var height = element.clientHeight; + + element._originalLeft = left - parseFloat(element.style.left || 0); + element._originalTop = top - parseFloat(element.style.top || 0); + element._originalWidth = element.style.width; + element._originalHeight = element.style.height; + + element.style.position = 'absolute'; + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.width = width + 'px'; + element.style.height = height + 'px'; + return element; + }, + + relativize: function(element) { + element = $(element); + if (Element.getStyle(element, 'position') == 'relative') return element; + + element.style.position = 'relative'; + var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); + var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); + + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.height = element._originalHeight; + element.style.width = element._originalWidth; + return element; + }, + + cumulativeScrollOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + getOffsetParent: function(element) { + if (element.offsetParent) return $(element.offsetParent); + if (element == document.body) return $(element); + + while ((element = element.parentNode) && element != document.body) + if (Element.getStyle(element, 'position') != 'static') + return $(element); + + return $(document.body); + }, + + viewportOffset: function(forElement) { + var valueT = 0, valueL = 0; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + + if (element.offsetParent == document.body && + Element.getStyle(element, 'position') == 'absolute') break; + + } while (element = element.offsetParent); + + element = forElement; + do { + if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } + } while (element = element.parentNode); + + return Element._returnOffset(valueL, valueT); + }, + + clonePosition: function(element, source) { + var options = Object.extend({ + setLeft: true, + setTop: true, + setWidth: true, + setHeight: true, + offsetTop: 0, + offsetLeft: 0 + }, arguments[2] || { }); + + source = $(source); + var p = Element.viewportOffset(source); + + element = $(element); + var delta = [0, 0]; + var parent = null; + if (Element.getStyle(element, 'position') == 'absolute') { + parent = Element.getOffsetParent(element); + delta = Element.viewportOffset(parent); + } + + if (parent == document.body) { + delta[0] -= document.body.offsetLeft; + delta[1] -= document.body.offsetTop; + } + + if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; + if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; + if (options.setWidth) element.style.width = source.offsetWidth + 'px'; + if (options.setHeight) element.style.height = source.offsetHeight + 'px'; + return element; + } +}; + +Object.extend(Element.Methods, { + getElementsBySelector: Element.Methods.select, + + childElements: Element.Methods.immediateDescendants +}); + +Element._attributeTranslations = { + write: { + names: { + className: 'class', + htmlFor: 'for' + }, + values: { } + } +}; + +if (Prototype.Browser.Opera) { + Element.Methods.getStyle = Element.Methods.getStyle.wrap( + function(proceed, element, style) { + switch (style) { + case 'left': case 'top': case 'right': case 'bottom': + if (proceed(element, 'position') === 'static') return null; + case 'height': case 'width': + if (!Element.visible(element)) return null; + + var dim = parseInt(proceed(element, style), 10); + + if (dim !== element['offset' + style.capitalize()]) + return dim + 'px'; + + var properties; + if (style === 'height') { + properties = ['border-top-width', 'padding-top', + 'padding-bottom', 'border-bottom-width']; + } + else { + properties = ['border-left-width', 'padding-left', + 'padding-right', 'border-right-width']; + } + return properties.inject(dim, function(memo, property) { + var val = proceed(element, property); + return val === null ? memo : memo - parseInt(val, 10); + }) + 'px'; + default: return proceed(element, style); + } + } + ); + + Element.Methods.readAttribute = Element.Methods.readAttribute.wrap( + function(proceed, element, attribute) { + if (attribute === 'title') return element.title; + return proceed(element, attribute); + } + ); +} + +else if (Prototype.Browser.IE) { + Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap( + function(proceed, element) { + element = $(element); + try { element.offsetParent } + catch(e) { return $(document.body) } + var position = element.getStyle('position'); + if (position !== 'static') return proceed(element); + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + } + ); + + $w('positionedOffset viewportOffset').each(function(method) { + Element.Methods[method] = Element.Methods[method].wrap( + function(proceed, element) { + element = $(element); + try { element.offsetParent } + catch(e) { return Element._returnOffset(0,0) } + var position = element.getStyle('position'); + if (position !== 'static') return proceed(element); + var offsetParent = element.getOffsetParent(); + if (offsetParent && offsetParent.getStyle('position') === 'fixed') + offsetParent.setStyle({ zoom: 1 }); + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + } + ); + }); + + Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap( + function(proceed, element) { + try { element.offsetParent } + catch(e) { return Element._returnOffset(0,0) } + return proceed(element); + } + ); + + Element.Methods.getStyle = function(element, style) { + element = $(element); + style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize(); + var value = element.style[style]; + if (!value && element.currentStyle) value = element.currentStyle[style]; + + if (style == 'opacity') { + if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if (value[1]) return parseFloat(value[1]) / 100; + return 1.0; + } + + if (value == 'auto') { + if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none')) + return element['offset' + style.capitalize()] + 'px'; + return null; + } + return value; + }; + + Element.Methods.setOpacity = function(element, value) { + function stripAlpha(filter){ + return filter.replace(/alpha\([^\)]*\)/gi,''); + } + element = $(element); + var currentStyle = element.currentStyle; + if ((currentStyle && !currentStyle.hasLayout) || + (!currentStyle && element.style.zoom == 'normal')) + element.style.zoom = 1; + + var filter = element.getStyle('filter'), style = element.style; + if (value == 1 || value === '') { + (filter = stripAlpha(filter)) ? + style.filter = filter : style.removeAttribute('filter'); + return element; + } else if (value < 0.00001) value = 0; + style.filter = stripAlpha(filter) + + 'alpha(opacity=' + (value * 100) + ')'; + return element; + }; + + Element._attributeTranslations = (function(){ + + var classProp = 'className'; + var forProp = 'for'; + + var el = document.createElement('div'); + + el.setAttribute(classProp, 'x'); + + if (el.className !== 'x') { + el.setAttribute('class', 'x'); + if (el.className === 'x') { + classProp = 'class'; + } + } + el = null; + + el = document.createElement('label'); + el.setAttribute(forProp, 'x'); + if (el.htmlFor !== 'x') { + el.setAttribute('htmlFor', 'x'); + if (el.htmlFor === 'x') { + forProp = 'htmlFor'; + } + } + el = null; + + return { + read: { + names: { + 'class': classProp, + 'className': classProp, + 'for': forProp, + 'htmlFor': forProp + }, + values: { + _getAttr: function(element, attribute) { + return element.getAttribute(attribute); + }, + _getAttr2: function(element, attribute) { + return element.getAttribute(attribute, 2); + }, + _getAttrNode: function(element, attribute) { + var node = element.getAttributeNode(attribute); + return node ? node.value : ""; + }, + _getEv: (function(){ + + var el = document.createElement('div'); + el.onclick = Prototype.emptyFunction; + var value = el.getAttribute('onclick'); + var f; + + if (String(value).indexOf('{') > -1) { + f = function(element, attribute) { + attribute = element.getAttribute(attribute); + if (!attribute) return null; + attribute = attribute.toString(); + attribute = attribute.split('{')[1]; + attribute = attribute.split('}')[0]; + return attribute.strip(); + }; + } + else if (value === '') { + f = function(element, attribute) { + attribute = element.getAttribute(attribute); + if (!attribute) return null; + return attribute.strip(); + }; + } + el = null; + return f; + })(), + _flag: function(element, attribute) { + return $(element).hasAttribute(attribute) ? attribute : null; + }, + style: function(element) { + return element.style.cssText.toLowerCase(); + }, + title: function(element) { + return element.title; + } + } + } + } + })(); + + Element._attributeTranslations.write = { + names: Object.extend({ + cellpadding: 'cellPadding', + cellspacing: 'cellSpacing' + }, Element._attributeTranslations.read.names), + values: { + checked: function(element, value) { + element.checked = !!value; + }, + + style: function(element, value) { + element.style.cssText = value ? value : ''; + } + } + }; + + Element._attributeTranslations.has = {}; + + $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' + + 'encType maxLength readOnly longDesc frameBorder').each(function(attr) { + Element._attributeTranslations.write.names[attr.toLowerCase()] = attr; + Element._attributeTranslations.has[attr.toLowerCase()] = attr; + }); + + (function(v) { + Object.extend(v, { + href: v._getAttr2, + src: v._getAttr2, + type: v._getAttr, + action: v._getAttrNode, + disabled: v._flag, + checked: v._flag, + readonly: v._flag, + multiple: v._flag, + onload: v._getEv, + onunload: v._getEv, + onclick: v._getEv, + ondblclick: v._getEv, + onmousedown: v._getEv, + onmouseup: v._getEv, + onmouseover: v._getEv, + onmousemove: v._getEv, + onmouseout: v._getEv, + onfocus: v._getEv, + onblur: v._getEv, + onkeypress: v._getEv, + onkeydown: v._getEv, + onkeyup: v._getEv, + onsubmit: v._getEv, + onreset: v._getEv, + onselect: v._getEv, + onchange: v._getEv + }); + })(Element._attributeTranslations.read.values); + + if (Prototype.BrowserFeatures.ElementExtensions) { + (function() { + function _descendants(element) { + var nodes = element.getElementsByTagName('*'), results = []; + for (var i = 0, node; node = nodes[i]; i++) + if (node.tagName !== "!") // Filter out comment nodes. + results.push(node); + return results; + } + + Element.Methods.down = function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return element.firstDescendant(); + return Object.isNumber(expression) ? _descendants(element)[expression] : + Element.select(element, expression)[index || 0]; + } + })(); + } + +} + +else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + element.style.opacity = (value == 1) ? 0.999999 : + (value === '') ? '' : (value < 0.00001) ? 0 : value; + return element; + }; +} + +else if (Prototype.Browser.WebKit) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + + if (value == 1) + if(element.tagName.toUpperCase() == 'IMG' && element.width) { + element.width++; element.width--; + } else try { + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch (e) { } + + return element; + }; + + Element.Methods.cumulativeOffset = function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return Element._returnOffset(valueL, valueT); + }; +} + +if ('outerHTML' in document.documentElement) { + Element.Methods.replace = function(element, content) { + element = $(element); + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + element.parentNode.replaceChild(content, element); + return element; + } + + content = Object.toHTML(content); + var parent = element.parentNode, tagName = parent.tagName.toUpperCase(); + + if (Element._insertionTranslations.tags[tagName]) { + var nextSibling = element.next(); + var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + parent.removeChild(element); + if (nextSibling) + fragments.each(function(node) { parent.insertBefore(node, nextSibling) }); + else + fragments.each(function(node) { parent.appendChild(node) }); + } + else element.outerHTML = content.stripScripts(); + + content.evalScripts.bind(content).defer(); + return element; + }; +} + +Element._returnOffset = function(l, t) { + var result = [l, t]; + result.left = l; + result.top = t; + return result; +}; + +Element._getContentFromAnonymousElement = function(tagName, html) { + var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; + if (t) { + div.innerHTML = t[0] + html + t[1]; + t[2].times(function() { div = div.firstChild }); + } else div.innerHTML = html; + return $A(div.childNodes); +}; + +Element._insertionTranslations = { + before: function(element, node) { + element.parentNode.insertBefore(node, element); + }, + top: function(element, node) { + element.insertBefore(node, element.firstChild); + }, + bottom: function(element, node) { + element.appendChild(node); + }, + after: function(element, node) { + element.parentNode.insertBefore(node, element.nextSibling); + }, + tags: { + TABLE: ['<table>', '</table>', 1], + TBODY: ['<table><tbody>', '</tbody></table>', 2], + TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3], + TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4], + SELECT: ['<select>', '</select>', 1] + } +}; + +(function() { + var tags = Element._insertionTranslations.tags; + Object.extend(tags, { + THEAD: tags.TBODY, + TFOOT: tags.TBODY, + TH: tags.TD + }); +})(); + +Element.Methods.Simulated = { + hasAttribute: function(element, attribute) { + attribute = Element._attributeTranslations.has[attribute] || attribute; + var node = $(element).getAttributeNode(attribute); + return !!(node && node.specified); + } +}; + +Element.Methods.ByTag = { }; + +Object.extend(Element, Element.Methods); + +(function(div) { + + if (!Prototype.BrowserFeatures.ElementExtensions && div['__proto__']) { + window.HTMLElement = { }; + window.HTMLElement.prototype = div['__proto__']; + Prototype.BrowserFeatures.ElementExtensions = true; + } + + div = null; + +})(document.createElement('div')) + +Element.extend = (function() { + + function checkDeficiency(tagName) { + if (typeof window.Element != 'undefined') { + var proto = window.Element.prototype; + if (proto) { + var id = '_' + (Math.random()+'').slice(2); + var el = document.createElement(tagName); + proto[id] = 'x'; + var isBuggy = (el[id] !== 'x'); + delete proto[id]; + el = null; + return isBuggy; + } + } + return false; + } + + function extendElementWith(element, methods) { + for (var property in methods) { + var value = methods[property]; + if (Object.isFunction(value) && !(property in element)) + element[property] = value.methodize(); + } + } + + var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object'); + + if (Prototype.BrowserFeatures.SpecificElementExtensions) { + if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY) { + return function(element) { + if (element && typeof element._extendedByPrototype == 'undefined') { + var t = element.tagName; + if (t && (/^(?:object|applet|embed)$/i.test(t))) { + extendElementWith(element, Element.Methods); + extendElementWith(element, Element.Methods.Simulated); + extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]); + } + } + return element; + } + } + return Prototype.K; + } + + var Methods = { }, ByTag = Element.Methods.ByTag; + + var extend = Object.extend(function(element) { + if (!element || typeof element._extendedByPrototype != 'undefined' || + element.nodeType != 1 || element == window) return element; + + var methods = Object.clone(Methods), + tagName = element.tagName.toUpperCase(); + + if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); + + extendElementWith(element, methods); + + element._extendedByPrototype = Prototype.emptyFunction; + return element; + + }, { + refresh: function() { + if (!Prototype.BrowserFeatures.ElementExtensions) { + Object.extend(Methods, Element.Methods); + Object.extend(Methods, Element.Methods.Simulated); + } + } + }); + + extend.refresh(); + return extend; +})(); + +Element.hasAttribute = function(element, attribute) { + if (element.hasAttribute) return element.hasAttribute(attribute); + return Element.Methods.Simulated.hasAttribute(element, attribute); +}; + +Element.addMethods = function(methods) { + var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag; + + if (!methods) { + Object.extend(Form, Form.Methods); + Object.extend(Form.Element, Form.Element.Methods); + Object.extend(Element.Methods.ByTag, { + "FORM": Object.clone(Form.Methods), + "INPUT": Object.clone(Form.Element.Methods), + "SELECT": Object.clone(Form.Element.Methods), + "TEXTAREA": Object.clone(Form.Element.Methods) + }); + } + + if (arguments.length == 2) { + var tagName = methods; + methods = arguments[1]; + } + + if (!tagName) Object.extend(Element.Methods, methods || { }); + else { + if (Object.isArray(tagName)) tagName.each(extend); + else extend(tagName); + } + + function extend(tagName) { + tagName = tagName.toUpperCase(); + if (!Element.Methods.ByTag[tagName]) + Element.Methods.ByTag[tagName] = { }; + Object.extend(Element.Methods.ByTag[tagName], methods); + } + + function copy(methods, destination, onlyIfAbsent) { + onlyIfAbsent = onlyIfAbsent || false; + for (var property in methods) { + var value = methods[property]; + if (!Object.isFunction(value)) continue; + if (!onlyIfAbsent || !(property in destination)) + destination[property] = value.methodize(); + } + } + + function findDOMClass(tagName) { + var klass; + var trans = { + "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph", + "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList", + "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading", + "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote", + "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION": + "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD": + "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR": + "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET": + "FrameSet", "IFRAME": "IFrame" + }; + if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName.capitalize() + 'Element'; + if (window[klass]) return window[klass]; + + var element = document.createElement(tagName); + var proto = element['__proto__'] || element.constructor.prototype; + element = null; + return proto; + } + + var elementPrototype = window.HTMLElement ? HTMLElement.prototype : + Element.prototype; + + if (F.ElementExtensions) { + copy(Element.Methods, elementPrototype); + copy(Element.Methods.Simulated, elementPrototype, true); + } + + if (F.SpecificElementExtensions) { + for (var tag in Element.Methods.ByTag) { + var klass = findDOMClass(tag); + if (Object.isUndefined(klass)) continue; + copy(T[tag], klass.prototype); + } + } + + Object.extend(Element, Element.Methods); + delete Element.ByTag; + + if (Element.extend.refresh) Element.extend.refresh(); + Element.cache = { }; +}; + + +document.viewport = { + + getDimensions: function() { + return { width: this.getWidth(), height: this.getHeight() }; + }, + + getScrollOffsets: function() { + return Element._returnOffset( + window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, + window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); + } +}; + +(function(viewport) { + var B = Prototype.Browser, doc = document, element, property = {}; + + function getRootElement() { + if (B.WebKit && !doc.evaluate) + return document; + + if (B.Opera && window.parseFloat(window.opera.version()) < 9.5) + return document.body; + + return document.documentElement; + } + + function define(D) { + if (!element) element = getRootElement(); + + property[D] = 'client' + D; + + viewport['get' + D] = function() { return element[property[D]] }; + return viewport['get' + D](); + } + + viewport.getWidth = define.curry('Width'); + + viewport.getHeight = define.curry('Height'); +})(document.viewport); + + +Element.Storage = { + UID: 1 +}; + +Element.addMethods({ + getStorage: function(element) { + if (!(element = $(element))) return; + + var uid; + if (element === window) { + uid = 0; + } else { + if (typeof element._prototypeUID === "undefined") + element._prototypeUID = [Element.Storage.UID++]; + uid = element._prototypeUID[0]; + } + + if (!Element.Storage[uid]) + Element.Storage[uid] = $H(); + + return Element.Storage[uid]; + }, + + store: function(element, key, value) { + if (!(element = $(element))) return; + + if (arguments.length === 2) { + Element.getStorage(element).update(key); + } else { + Element.getStorage(element).set(key, value); + } + + return element; + }, + + retrieve: function(element, key, defaultValue) { + if (!(element = $(element))) return; + var hash = Element.getStorage(element), value = hash.get(key); + + if (Object.isUndefined(value)) { + hash.set(key, defaultValue); + value = defaultValue; + } + + return value; + }, + + clone: function(element, deep) { + if (!(element = $(element))) return; + var clone = element.cloneNode(deep); + clone._prototypeUID = void 0; + if (deep) { + var descendants = Element.select(clone, '*'), + i = descendants.length; + while (i--) { + descendants[i]._prototypeUID = void 0; + } + } + return Element.extend(clone); + } +}); +/* Portions of the Selector class are derived from Jack Slocum's DomQuery, + * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style + * license. Please see http://www.yui-ext.com/ for more information. */ + +var Selector = Class.create({ + initialize: function(expression) { + this.expression = expression.strip(); + + if (this.shouldUseSelectorsAPI()) { + this.mode = 'selectorsAPI'; + } else if (this.shouldUseXPath()) { + this.mode = 'xpath'; + this.compileXPathMatcher(); + } else { + this.mode = "normal"; + this.compileMatcher(); + } + + }, + + shouldUseXPath: (function() { + + var IS_DESCENDANT_SELECTOR_BUGGY = (function(){ + var isBuggy = false; + if (document.evaluate && window.XPathResult) { + var el = document.createElement('div'); + el.innerHTML = '<ul><li></li></ul><div><ul><li></li></ul></div>'; + + var xpath = ".//*[local-name()='ul' or local-name()='UL']" + + "//*[local-name()='li' or local-name()='LI']"; + + var result = document.evaluate(xpath, el, null, + XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + + isBuggy = (result.snapshotLength !== 2); + el = null; + } + return isBuggy; + })(); + + return function() { + if (!Prototype.BrowserFeatures.XPath) return false; + + var e = this.expression; + + if (Prototype.Browser.WebKit && + (e.include("-of-type") || e.include(":empty"))) + return false; + + if ((/(\[[\w-]*?:|:checked)/).test(e)) + return false; + + if (IS_DESCENDANT_SELECTOR_BUGGY) return false; + + return true; + } + + })(), + + shouldUseSelectorsAPI: function() { + if (!Prototype.BrowserFeatures.SelectorsAPI) return false; + + if (Selector.CASE_INSENSITIVE_CLASS_NAMES) return false; + + if (!Selector._div) Selector._div = new Element('div'); + + try { + Selector._div.querySelector(this.expression); + } catch(e) { + return false; + } + + return true; + }, + + compileMatcher: function() { + var e = this.expression, ps = Selector.patterns, h = Selector.handlers, + c = Selector.criteria, le, p, m, len = ps.length, name; + + if (Selector._cache[e]) { + this.matcher = Selector._cache[e]; + return; + } + + this.matcher = ["this.matcher = function(root) {", + "var r = root, h = Selector.handlers, c = false, n;"]; + + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i = 0; i<len; i++) { + p = ps[i].re; + name = ps[i].name; + if (m = e.match(p)) { + this.matcher.push(Object.isFunction(c[name]) ? c[name](m) : + new Template(c[name]).evaluate(m)); + e = e.replace(m[0], ''); + break; + } + } + } + + this.matcher.push("return h.unique(n);\n}"); + eval(this.matcher.join('\n')); + Selector._cache[this.expression] = this.matcher; + }, + + compileXPathMatcher: function() { + var e = this.expression, ps = Selector.patterns, + x = Selector.xpath, le, m, len = ps.length, name; + + if (Selector._cache[e]) { + this.xpath = Selector._cache[e]; return; + } + + this.matcher = ['.//*']; + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i = 0; i<len; i++) { + name = ps[i].name; + if (m = e.match(ps[i].re)) { + this.matcher.push(Object.isFunction(x[name]) ? x[name](m) : + new Template(x[name]).evaluate(m)); + e = e.replace(m[0], ''); + break; + } + } + } + + this.xpath = this.matcher.join(''); + Selector._cache[this.expression] = this.xpath; + }, + + findElements: function(root) { + root = root || document; + var e = this.expression, results; + + switch (this.mode) { + case 'selectorsAPI': + if (root !== document) { + var oldId = root.id, id = $(root).identify(); + id = id.replace(/([\.:])/g, "\\$1"); + e = "#" + id + " " + e; + } + + results = $A(root.querySelectorAll(e)).map(Element.extend); + root.id = oldId; + + return results; + case 'xpath': + return document._getElementsByXPath(this.xpath, root); + default: + return this.matcher(root); + } + }, + + match: function(element) { + this.tokens = []; + + var e = this.expression, ps = Selector.patterns, as = Selector.assertions; + var le, p, m, len = ps.length, name; + + while (e && le !== e && (/\S/).test(e)) { + le = e; + for (var i = 0; i<len; i++) { + p = ps[i].re; + name = ps[i].name; + if (m = e.match(p)) { + if (as[name]) { + this.tokens.push([name, Object.clone(m)]); + e = e.replace(m[0], ''); + } else { + return this.findElements(document).include(element); + } + } + } + } + + var match = true, name, matches; + for (var i = 0, token; token = this.tokens[i]; i++) { + name = token[0], matches = token[1]; + if (!Selector.assertions[name](element, matches)) { + match = false; break; + } + } + + return match; + }, + + toString: function() { + return this.expression; + }, + + inspect: function() { + return "#<Selector:" + this.expression.inspect() + ">"; + } +}); + +if (Prototype.BrowserFeatures.SelectorsAPI && + document.compatMode === 'BackCompat') { + Selector.CASE_INSENSITIVE_CLASS_NAMES = (function(){ + var div = document.createElement('div'), + span = document.createElement('span'); + + div.id = "prototype_test_id"; + span.className = 'Test'; + div.appendChild(span); + var isIgnored = (div.querySelector('#prototype_test_id .test') !== null); + div = span = null; + return isIgnored; + })(); +} + +Object.extend(Selector, { + _cache: { }, + + xpath: { + descendant: "//*", + child: "/*", + adjacent: "/following-sibling::*[1]", + laterSibling: '/following-sibling::*', + tagName: function(m) { + if (m[1] == '*') return ''; + return "[local-name()='" + m[1].toLowerCase() + + "' or local-name()='" + m[1].toUpperCase() + "']"; + }, + className: "[contains(concat(' ', @class, ' '), ' #{1} ')]", + id: "[@id='#{1}']", + attrPresence: function(m) { + m[1] = m[1].toLowerCase(); + return new Template("[@#{1}]").evaluate(m); + }, + attr: function(m) { + m[1] = m[1].toLowerCase(); + m[3] = m[5] || m[6]; + return new Template(Selector.xpath.operators[m[2]]).evaluate(m); + }, + pseudo: function(m) { + var h = Selector.xpath.pseudos[m[1]]; + if (!h) return ''; + if (Object.isFunction(h)) return h(m); + return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m); + }, + operators: { + '=': "[@#{1}='#{3}']", + '!=': "[@#{1}!='#{3}']", + '^=': "[starts-with(@#{1}, '#{3}')]", + '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']", + '*=': "[contains(@#{1}, '#{3}')]", + '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]", + '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]" + }, + pseudos: { + 'first-child': '[not(preceding-sibling::*)]', + 'last-child': '[not(following-sibling::*)]', + 'only-child': '[not(preceding-sibling::* or following-sibling::*)]', + 'empty': "[count(*) = 0 and (count(text()) = 0)]", + 'checked': "[@checked]", + 'disabled': "[(@disabled) and (@type!='hidden')]", + 'enabled': "[not(@disabled) and (@type!='hidden')]", + 'not': function(m) { + var e = m[6], p = Selector.patterns, + x = Selector.xpath, le, v, len = p.length, name; + + var exclusion = []; + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i = 0; i<len; i++) { + name = p[i].name + if (m = e.match(p[i].re)) { + v = Object.isFunction(x[name]) ? x[name](m) : new Template(x[name]).evaluate(m); + exclusion.push("(" + v.substring(1, v.length - 1) + ")"); + e = e.replace(m[0], ''); + break; + } + } + } + return "[not(" + exclusion.join(" and ") + ")]"; + }, + 'nth-child': function(m) { + return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m); + }, + 'nth-last-child': function(m) { + return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m); + }, + 'nth-of-type': function(m) { + return Selector.xpath.pseudos.nth("position() ", m); + }, + 'nth-last-of-type': function(m) { + return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m); + }, + 'first-of-type': function(m) { + m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m); + }, + 'last-of-type': function(m) { + m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m); + }, + 'only-of-type': function(m) { + var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m); + }, + nth: function(fragment, m) { + var mm, formula = m[6], predicate; + if (formula == 'even') formula = '2n+0'; + if (formula == 'odd') formula = '2n+1'; + if (mm = formula.match(/^(\d+)$/)) // digit only + return '[' + fragment + "= " + mm[1] + ']'; + if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b + if (mm[1] == "-") mm[1] = -1; + var a = mm[1] ? Number(mm[1]) : 1; + var b = mm[2] ? Number(mm[2]) : 0; + predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " + + "((#{fragment} - #{b}) div #{a} >= 0)]"; + return new Template(predicate).evaluate({ + fragment: fragment, a: a, b: b }); + } + } + } + }, + + criteria: { + tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', + className: 'n = h.className(n, r, "#{1}", c); c = false;', + id: 'n = h.id(n, r, "#{1}", c); c = false;', + attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;', + attr: function(m) { + m[3] = (m[5] || m[6]); + return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m); + }, + pseudo: function(m) { + if (m[6]) m[6] = m[6].replace(/"/g, '\\"'); + return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m); + }, + descendant: 'c = "descendant";', + child: 'c = "child";', + adjacent: 'c = "adjacent";', + laterSibling: 'c = "laterSibling";' + }, + + patterns: [ + { name: 'laterSibling', re: /^\s*~\s*/ }, + { name: 'child', re: /^\s*>\s*/ }, + { name: 'adjacent', re: /^\s*\+\s*/ }, + { name: 'descendant', re: /^\s/ }, + + { name: 'tagName', re: /^\s*(\*|[\w\-]+)(\b|$)?/ }, + { name: 'id', re: /^#([\w\-\*]+)(\b|$)/ }, + { name: 'className', re: /^\.([\w\-\*]+)(\b|$)/ }, + { name: 'pseudo', re: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/ }, + { name: 'attrPresence', re: /^\[((?:[\w-]+:)?[\w-]+)\]/ }, + { name: 'attr', re: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/ } + ], + + assertions: { + tagName: function(element, matches) { + return matches[1].toUpperCase() == element.tagName.toUpperCase(); + }, + + className: function(element, matches) { + return Element.hasClassName(element, matches[1]); + }, + + id: function(element, matches) { + return element.id === matches[1]; + }, + + attrPresence: function(element, matches) { + return Element.hasAttribute(element, matches[1]); + }, + + attr: function(element, matches) { + var nodeValue = Element.readAttribute(element, matches[1]); + return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]); + } + }, + + handlers: { + concat: function(a, b) { + for (var i = 0, node; node = b[i]; i++) + a.push(node); + return a; + }, + + mark: function(nodes) { + var _true = Prototype.emptyFunction; + for (var i = 0, node; node = nodes[i]; i++) + node._countedByPrototype = _true; + return nodes; + }, + + unmark: (function(){ + + var PROPERTIES_ATTRIBUTES_MAP = (function(){ + var el = document.createElement('div'), + isBuggy = false, + propName = '_countedByPrototype', + value = 'x' + el[propName] = value; + isBuggy = (el.getAttribute(propName) === value); + el = null; + return isBuggy; + })(); + + return PROPERTIES_ATTRIBUTES_MAP ? + function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node.removeAttribute('_countedByPrototype'); + return nodes; + } : + function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node._countedByPrototype = void 0; + return nodes; + } + })(), + + index: function(parentNode, reverse, ofType) { + parentNode._countedByPrototype = Prototype.emptyFunction; + if (reverse) { + for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) { + var node = nodes[i]; + if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++; + } + } else { + for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++) + if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++; + } + }, + + unique: function(nodes) { + if (nodes.length == 0) return nodes; + var results = [], n; + for (var i = 0, l = nodes.length; i < l; i++) + if (typeof (n = nodes[i])._countedByPrototype == 'undefined') { + n._countedByPrototype = Prototype.emptyFunction; + results.push(Element.extend(n)); + } + return Selector.handlers.unmark(results); + }, + + descendant: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + h.concat(results, node.getElementsByTagName('*')); + return results; + }, + + child: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) { + for (var j = 0, child; child = node.childNodes[j]; j++) + if (child.nodeType == 1 && child.tagName != '!') results.push(child); + } + return results; + }, + + adjacent: function(nodes) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + var next = this.nextElementSibling(node); + if (next) results.push(next); + } + return results; + }, + + laterSibling: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + h.concat(results, Element.nextSiblings(node)); + return results; + }, + + nextElementSibling: function(node) { + while (node = node.nextSibling) + if (node.nodeType == 1) return node; + return null; + }, + + previousElementSibling: function(node) { + while (node = node.previousSibling) + if (node.nodeType == 1) return node; + return null; + }, + + tagName: function(nodes, root, tagName, combinator) { + var uTagName = tagName.toUpperCase(); + var results = [], h = Selector.handlers; + if (nodes) { + if (combinator) { + if (combinator == "descendant") { + for (var i = 0, node; node = nodes[i]; i++) + h.concat(results, node.getElementsByTagName(tagName)); + return results; + } else nodes = this[combinator](nodes); + if (tagName == "*") return nodes; + } + for (var i = 0, node; node = nodes[i]; i++) + if (node.tagName.toUpperCase() === uTagName) results.push(node); + return results; + } else return root.getElementsByTagName(tagName); + }, + + id: function(nodes, root, id, combinator) { + var targetNode = $(id), h = Selector.handlers; + + if (root == document) { + if (!targetNode) return []; + if (!nodes) return [targetNode]; + } else { + if (!root.sourceIndex || root.sourceIndex < 1) { + var nodes = root.getElementsByTagName('*'); + for (var j = 0, node; node = nodes[j]; j++) { + if (node.id === id) return [node]; + } + } + } + + if (nodes) { + if (combinator) { + if (combinator == 'child') { + for (var i = 0, node; node = nodes[i]; i++) + if (targetNode.parentNode == node) return [targetNode]; + } else if (combinator == 'descendant') { + for (var i = 0, node; node = nodes[i]; i++) + if (Element.descendantOf(targetNode, node)) return [targetNode]; + } else if (combinator == 'adjacent') { + for (var i = 0, node; node = nodes[i]; i++) + if (Selector.handlers.previousElementSibling(targetNode) == node) + return [targetNode]; + } else nodes = h[combinator](nodes); + } + for (var i = 0, node; node = nodes[i]; i++) + if (node == targetNode) return [targetNode]; + return []; + } + return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : []; + }, + + className: function(nodes, root, className, combinator) { + if (nodes && combinator) nodes = this[combinator](nodes); + return Selector.handlers.byClassName(nodes, root, className); + }, + + byClassName: function(nodes, root, className) { + if (!nodes) nodes = Selector.handlers.descendant([root]); + var needle = ' ' + className + ' '; + for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) { + nodeClassName = node.className; + if (nodeClassName.length == 0) continue; + if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle)) + results.push(node); + } + return results; + }, + + attrPresence: function(nodes, root, attr, combinator) { + if (!nodes) nodes = root.getElementsByTagName("*"); + if (nodes && combinator) nodes = this[combinator](nodes); + var results = []; + for (var i = 0, node; node = nodes[i]; i++) + if (Element.hasAttribute(node, attr)) results.push(node); + return results; + }, + + attr: function(nodes, root, attr, value, operator, combinator) { + if (!nodes) nodes = root.getElementsByTagName("*"); + if (nodes && combinator) nodes = this[combinator](nodes); + var handler = Selector.operators[operator], results = []; + for (var i = 0, node; node = nodes[i]; i++) { + var nodeValue = Element.readAttribute(node, attr); + if (nodeValue === null) continue; + if (handler(nodeValue, value)) results.push(node); + } + return results; + }, + + pseudo: function(nodes, name, value, root, combinator) { + if (nodes && combinator) nodes = this[combinator](nodes); + if (!nodes) nodes = root.getElementsByTagName("*"); + return Selector.pseudos[name](nodes, value, root); + } + }, + + pseudos: { + 'first-child': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (Selector.handlers.previousElementSibling(node)) continue; + results.push(node); + } + return results; + }, + 'last-child': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (Selector.handlers.nextElementSibling(node)) continue; + results.push(node); + } + return results; + }, + 'only-child': function(nodes, value, root) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!h.previousElementSibling(node) && !h.nextElementSibling(node)) + results.push(node); + return results; + }, + 'nth-child': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root); + }, + 'nth-last-child': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, true); + }, + 'nth-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, false, true); + }, + 'nth-last-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, true, true); + }, + 'first-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, "1", root, false, true); + }, + 'last-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, "1", root, true, true); + }, + 'only-of-type': function(nodes, formula, root) { + var p = Selector.pseudos; + return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root); + }, + + getIndices: function(a, b, total) { + if (a == 0) return b > 0 ? [b] : []; + return $R(1, total).inject([], function(memo, i) { + if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i); + return memo; + }); + }, + + nth: function(nodes, formula, root, reverse, ofType) { + if (nodes.length == 0) return []; + if (formula == 'even') formula = '2n+0'; + if (formula == 'odd') formula = '2n+1'; + var h = Selector.handlers, results = [], indexed = [], m; + h.mark(nodes); + for (var i = 0, node; node = nodes[i]; i++) { + if (!node.parentNode._countedByPrototype) { + h.index(node.parentNode, reverse, ofType); + indexed.push(node.parentNode); + } + } + if (formula.match(/^\d+$/)) { // just a number + formula = Number(formula); + for (var i = 0, node; node = nodes[i]; i++) + if (node.nodeIndex == formula) results.push(node); + } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b + if (m[1] == "-") m[1] = -1; + var a = m[1] ? Number(m[1]) : 1; + var b = m[2] ? Number(m[2]) : 0; + var indices = Selector.pseudos.getIndices(a, b, nodes.length); + for (var i = 0, node, l = indices.length; node = nodes[i]; i++) { + for (var j = 0; j < l; j++) + if (node.nodeIndex == indices[j]) results.push(node); + } + } + h.unmark(nodes); + h.unmark(indexed); + return results; + }, + + 'empty': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (node.tagName == '!' || node.firstChild) continue; + results.push(node); + } + return results; + }, + + 'not': function(nodes, selector, root) { + var h = Selector.handlers, selectorType, m; + var exclusions = new Selector(selector).findElements(root); + h.mark(exclusions); + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!node._countedByPrototype) results.push(node); + h.unmark(exclusions); + return results; + }, + + 'enabled': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!node.disabled && (!node.type || node.type !== 'hidden')) + results.push(node); + return results; + }, + + 'disabled': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (node.disabled) results.push(node); + return results; + }, + + 'checked': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (node.checked) results.push(node); + return results; + } + }, + + operators: { + '=': function(nv, v) { return nv == v; }, + '!=': function(nv, v) { return nv != v; }, + '^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); }, + '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); }, + '*=': function(nv, v) { return nv == v || nv && nv.include(v); }, + '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); }, + '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() + + '-').include('-' + (v || "").toUpperCase() + '-'); } + }, + + split: function(expression) { + var expressions = []; + expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { + expressions.push(m[1].strip()); + }); + return expressions; + }, + + matchElements: function(elements, expression) { + var matches = $$(expression), h = Selector.handlers; + h.mark(matches); + for (var i = 0, results = [], element; element = elements[i]; i++) + if (element._countedByPrototype) results.push(element); + h.unmark(matches); + return results; + }, + + findElement: function(elements, expression, index) { + if (Object.isNumber(expression)) { + index = expression; expression = false; + } + return Selector.matchElements(elements, expression || '*')[index || 0]; + }, + + findChildElements: function(element, expressions) { + expressions = Selector.split(expressions.join(',')); + var results = [], h = Selector.handlers; + for (var i = 0, l = expressions.length, selector; i < l; i++) { + selector = new Selector(expressions[i].strip()); + h.concat(results, selector.findElements(element)); + } + return (l > 1) ? h.unique(results) : results; + } +}); + +if (Prototype.Browser.IE) { + Object.extend(Selector.handlers, { + concat: function(a, b) { + for (var i = 0, node; node = b[i]; i++) + if (node.tagName !== "!") a.push(node); + return a; + } + }); +} + +function $$() { + return Selector.findChildElements(document, $A(arguments)); +} + +var Form = { + reset: function(form) { + form = $(form); + form.reset(); + return form; + }, + + serializeElements: function(elements, options) { + if (typeof options != 'object') options = { hash: !!options }; + else if (Object.isUndefined(options.hash)) options.hash = true; + var key, value, submitted = false, submit = options.submit; + + var data = elements.inject({ }, function(result, element) { + if (!element.disabled && element.name) { + key = element.name; value = $(element).getValue(); + if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted && + submit !== false && (!submit || key == submit) && (submitted = true)))) { + if (key in result) { + if (!Object.isArray(result[key])) result[key] = [result[key]]; + result[key].push(value); + } + else result[key] = value; + } + } + return result; + }); + + return options.hash ? data : Object.toQueryString(data); + } +}; + +Form.Methods = { + serialize: function(form, options) { + return Form.serializeElements(Form.getElements(form), options); + }, + + getElements: function(form) { + var elements = $(form).getElementsByTagName('*'), + element, + arr = [ ], + serializers = Form.Element.Serializers; + for (var i = 0; element = elements[i]; i++) { + arr.push(element); + } + return arr.inject([], function(elements, child) { + if (serializers[child.tagName.toLowerCase()]) + elements.push(Element.extend(child)); + return elements; + }) + }, + + getInputs: function(form, typeName, name) { + form = $(form); + var inputs = form.getElementsByTagName('input'); + + if (!typeName && !name) return $A(inputs).map(Element.extend); + + for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { + var input = inputs[i]; + if ((typeName && input.type != typeName) || (name && input.name != name)) + continue; + matchingInputs.push(Element.extend(input)); + } + + return matchingInputs; + }, + + disable: function(form) { + form = $(form); + Form.getElements(form).invoke('disable'); + return form; + }, + + enable: function(form) { + form = $(form); + Form.getElements(form).invoke('enable'); + return form; + }, + + findFirstElement: function(form) { + var elements = $(form).getElements().findAll(function(element) { + return 'hidden' != element.type && !element.disabled; + }); + var firstByIndex = elements.findAll(function(element) { + return element.hasAttribute('tabIndex') && element.tabIndex >= 0; + }).sortBy(function(element) { return element.tabIndex }).first(); + + return firstByIndex ? firstByIndex : elements.find(function(element) { + return /^(?:input|select|textarea)$/i.test(element.tagName); + }); + }, + + focusFirstElement: function(form) { + form = $(form); + form.findFirstElement().activate(); + return form; + }, + + request: function(form, options) { + form = $(form), options = Object.clone(options || { }); + + var params = options.parameters, action = form.readAttribute('action') || ''; + if (action.blank()) action = window.location.href; + options.parameters = form.serialize(true); + + if (params) { + if (Object.isString(params)) params = params.toQueryParams(); + Object.extend(options.parameters, params); + } + + if (form.hasAttribute('method') && !options.method) + options.method = form.method; + + return new Ajax.Request(action, options); + } +}; + +/*--------------------------------------------------------------------------*/ + + +Form.Element = { + focus: function(element) { + $(element).focus(); + return element; + }, + + select: function(element) { + $(element).select(); + return element; + } +}; + +Form.Element.Methods = { + + serialize: function(element) { + element = $(element); + if (!element.disabled && element.name) { + var value = element.getValue(); + if (value != undefined) { + var pair = { }; + pair[element.name] = value; + return Object.toQueryString(pair); + } + } + return ''; + }, + + getValue: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + return Form.Element.Serializers[method](element); + }, + + setValue: function(element, value) { + element = $(element); + var method = element.tagName.toLowerCase(); + Form.Element.Serializers[method](element, value); + return element; + }, + + clear: function(element) { + $(element).value = ''; + return element; + }, + + present: function(element) { + return $(element).value != ''; + }, + + activate: function(element) { + element = $(element); + try { + element.focus(); + if (element.select && (element.tagName.toLowerCase() != 'input' || + !(/^(?:button|reset|submit)$/i.test(element.type)))) + element.select(); + } catch (e) { } + return element; + }, + + disable: function(element) { + element = $(element); + element.disabled = true; + return element; + }, + + enable: function(element) { + element = $(element); + element.disabled = false; + return element; + } +}; + +/*--------------------------------------------------------------------------*/ + +var Field = Form.Element; + +var $F = Form.Element.Methods.getValue; + +/*--------------------------------------------------------------------------*/ + +Form.Element.Serializers = { + input: function(element, value) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + return Form.Element.Serializers.inputSelector(element, value); + default: + return Form.Element.Serializers.textarea(element, value); + } + }, + + inputSelector: function(element, value) { + if (Object.isUndefined(value)) return element.checked ? element.value : null; + else element.checked = !!value; + }, + + textarea: function(element, value) { + if (Object.isUndefined(value)) return element.value; + else element.value = value; + }, + + select: function(element, value) { + if (Object.isUndefined(value)) + return this[element.type == 'select-one' ? + 'selectOne' : 'selectMany'](element); + else { + var opt, currentValue, single = !Object.isArray(value); + for (var i = 0, length = element.length; i < length; i++) { + opt = element.options[i]; + currentValue = this.optionValue(opt); + if (single) { + if (currentValue == value) { + opt.selected = true; + return; + } + } + else opt.selected = value.include(currentValue); + } + } + }, + + selectOne: function(element) { + var index = element.selectedIndex; + return index >= 0 ? this.optionValue(element.options[index]) : null; + }, + + selectMany: function(element) { + var values, length = element.length; + if (!length) return null; + + for (var i = 0, values = []; i < length; i++) { + var opt = element.options[i]; + if (opt.selected) values.push(this.optionValue(opt)); + } + return values; + }, + + optionValue: function(opt) { + return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; + } +}; + +/*--------------------------------------------------------------------------*/ + + +Abstract.TimedObserver = Class.create(PeriodicalExecuter, { + initialize: function($super, element, frequency, callback) { + $super(callback, frequency); + this.element = $(element); + this.lastValue = this.getValue(); + }, + + execute: function() { + var value = this.getValue(); + if (Object.isString(this.lastValue) && Object.isString(value) ? + this.lastValue != value : String(this.lastValue) != String(value)) { + this.callback(this.element, value); + this.lastValue = value; + } + } +}); + +Form.Element.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); + +/*--------------------------------------------------------------------------*/ + +Abstract.EventObserver = Class.create({ + initialize: function(element, callback) { + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + if (this.element.tagName.toLowerCase() == 'form') + this.registerFormCallbacks(); + else + this.registerCallback(this.element); + }, + + onElementEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + }, + + registerFormCallbacks: function() { + Form.getElements(this.element).each(this.registerCallback, this); + }, + + registerCallback: function(element) { + if (element.type) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + Event.observe(element, 'click', this.onElementEvent.bind(this)); + break; + default: + Event.observe(element, 'change', this.onElementEvent.bind(this)); + break; + } + } + } +}); + +Form.Element.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); +(function() { + + var Event = { + KEY_BACKSPACE: 8, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + KEY_HOME: 36, + KEY_END: 35, + KEY_PAGEUP: 33, + KEY_PAGEDOWN: 34, + KEY_INSERT: 45, + + cache: {} + }; + + var docEl = document.documentElement; + var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl + && 'onmouseleave' in docEl; + + var _isButton; + if (Prototype.Browser.IE) { + var buttonMap = { 0: 1, 1: 4, 2: 2 }; + _isButton = function(event, code) { + return event.button === buttonMap[code]; + }; + } else if (Prototype.Browser.WebKit) { + _isButton = function(event, code) { + switch (code) { + case 0: return event.which == 1 && !event.metaKey; + case 1: return event.which == 1 && event.metaKey; + default: return false; + } + }; + } else { + _isButton = function(event, code) { + return event.which ? (event.which === code + 1) : (event.button === code); + }; + } + + function isLeftClick(event) { return _isButton(event, 0) } + + function isMiddleClick(event) { return _isButton(event, 1) } + + function isRightClick(event) { return _isButton(event, 2) } + + function element(event) { + event = Event.extend(event); + + var node = event.target, type = event.type, + currentTarget = event.currentTarget; + + if (currentTarget && currentTarget.tagName) { + if (type === 'load' || type === 'error' || + (type === 'click' && currentTarget.tagName.toLowerCase() === 'input' + && currentTarget.type === 'radio')) + node = currentTarget; + } + + if (node.nodeType == Node.TEXT_NODE) + node = node.parentNode; + + return Element.extend(node); + } + + function findElement(event, expression) { + var element = Event.element(event); + if (!expression) return element; + var elements = [element].concat(element.ancestors()); + return Selector.findElement(elements, expression, 0); + } + + function pointer(event) { + return { x: pointerX(event), y: pointerY(event) }; + } + + function pointerX(event) { + var docElement = document.documentElement, + body = document.body || { scrollLeft: 0 }; + + return event.pageX || (event.clientX + + (docElement.scrollLeft || body.scrollLeft) - + (docElement.clientLeft || 0)); + } + + function pointerY(event) { + var docElement = document.documentElement, + body = document.body || { scrollTop: 0 }; + + return event.pageY || (event.clientY + + (docElement.scrollTop || body.scrollTop) - + (docElement.clientTop || 0)); + } + + + function stop(event) { + Event.extend(event); + event.preventDefault(); + event.stopPropagation(); + + event.stopped = true; + } + + Event.Methods = { + isLeftClick: isLeftClick, + isMiddleClick: isMiddleClick, + isRightClick: isRightClick, + + element: element, + findElement: findElement, + + pointer: pointer, + pointerX: pointerX, + pointerY: pointerY, + + stop: stop + }; + + + var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { + m[name] = Event.Methods[name].methodize(); + return m; + }); + + if (Prototype.Browser.IE) { + function _relatedTarget(event) { + var element; + switch (event.type) { + case 'mouseover': element = event.fromElement; break; + case 'mouseout': element = event.toElement; break; + default: return null; + } + return Element.extend(element); + } + + Object.extend(methods, { + stopPropagation: function() { this.cancelBubble = true }, + preventDefault: function() { this.returnValue = false }, + inspect: function() { return '[object Event]' } + }); + + Event.extend = function(event, element) { + if (!event) return false; + if (event._extendedByPrototype) return event; + + event._extendedByPrototype = Prototype.emptyFunction; + var pointer = Event.pointer(event); + + Object.extend(event, { + target: event.srcElement || element, + relatedTarget: _relatedTarget(event), + pageX: pointer.x, + pageY: pointer.y + }); + + return Object.extend(event, methods); + }; + } else { + Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__; + Object.extend(Event.prototype, methods); + Event.extend = Prototype.K; + } + + function _createResponder(element, eventName, handler) { + var registry = Element.retrieve(element, 'prototype_event_registry'); + + if (Object.isUndefined(registry)) { + CACHE.push(element); + registry = Element.retrieve(element, 'prototype_event_registry', $H()); + } + + var respondersForEvent = registry.get(eventName); + if (Object.isUndefined(respondersForEvent)) { + respondersForEvent = []; + registry.set(eventName, respondersForEvent); + } + + if (respondersForEvent.pluck('handler').include(handler)) return false; + + var responder; + if (eventName.include(":")) { + responder = function(event) { + if (Object.isUndefined(event.eventName)) + return false; + + if (event.eventName !== eventName) + return false; + + Event.extend(event, element); + handler.call(element, event); + }; + } else { + if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED && + (eventName === "mouseenter" || eventName === "mouseleave")) { + if (eventName === "mouseenter" || eventName === "mouseleave") { + responder = function(event) { + Event.extend(event, element); + + var parent = event.relatedTarget; + while (parent && parent !== element) { + try { parent = parent.parentNode; } + catch(e) { parent = element; } + } + + if (parent === element) return; + + handler.call(element, event); + }; + } + } else { + responder = function(event) { + Event.extend(event, element); + handler.call(element, event); + }; + } + } + + responder.handler = handler; + respondersForEvent.push(responder); + return responder; + } + + function _destroyCache() { + for (var i = 0, length = CACHE.length; i < length; i++) { + Event.stopObserving(CACHE[i]); + CACHE[i] = null; + } + } + + var CACHE = []; + + if (Prototype.Browser.IE) + window.attachEvent('onunload', _destroyCache); + + if (Prototype.Browser.WebKit) + window.addEventListener('unload', Prototype.emptyFunction, false); + + + var _getDOMEventName = Prototype.K; + + if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) { + _getDOMEventName = function(eventName) { + var translations = { mouseenter: "mouseover", mouseleave: "mouseout" }; + return eventName in translations ? translations[eventName] : eventName; + }; + } + + function observe(element, eventName, handler) { + element = $(element); + + var responder = _createResponder(element, eventName, handler); + + if (!responder) return element; + + if (eventName.include(':')) { + if (element.addEventListener) + element.addEventListener("dataavailable", responder, false); + else { + element.attachEvent("ondataavailable", responder); + element.attachEvent("onfilterchange", responder); + } + } else { + var actualEventName = _getDOMEventName(eventName); + + if (element.addEventListener) + element.addEventListener(actualEventName, responder, false); + else + element.attachEvent("on" + actualEventName, responder); + } + + return element; + } + + function stopObserving(element, eventName, handler) { + element = $(element); + + var registry = Element.retrieve(element, 'prototype_event_registry'); + + if (Object.isUndefined(registry)) return element; + + if (eventName && !handler) { + var responders = registry.get(eventName); + + if (Object.isUndefined(responders)) return element; + + responders.each( function(r) { + Element.stopObserving(element, eventName, r.handler); + }); + return element; + } else if (!eventName) { + registry.each( function(pair) { + var eventName = pair.key, responders = pair.value; + + responders.each( function(r) { + Element.stopObserving(element, eventName, r.handler); + }); + }); + return element; + } + + var responders = registry.get(eventName); + + if (!responders) return; + + var responder = responders.find( function(r) { return r.handler === handler; }); + if (!responder) return element; + + var actualEventName = _getDOMEventName(eventName); + + if (eventName.include(':')) { + if (element.removeEventListener) + element.removeEventListener("dataavailable", responder, false); + else { + element.detachEvent("ondataavailable", responder); + element.detachEvent("onfilterchange", responder); + } + } else { + if (element.removeEventListener) + element.removeEventListener(actualEventName, responder, false); + else + element.detachEvent('on' + actualEventName, responder); + } + + registry.set(eventName, responders.without(responder)); + + return element; + } + + function fire(element, eventName, memo, bubble) { + element = $(element); + + if (Object.isUndefined(bubble)) + bubble = true; + + if (element == document && document.createEvent && !element.dispatchEvent) + element = document.documentElement; + + var event; + if (document.createEvent) { + event = document.createEvent('HTMLEvents'); + event.initEvent('dataavailable', true, true); + } else { + event = document.createEventObject(); + event.eventType = bubble ? 'ondataavailable' : 'onfilterchange'; + } + + event.eventName = eventName; + event.memo = memo || { }; + + if (document.createEvent) + element.dispatchEvent(event); + else + element.fireEvent(event.eventType, event); + + return Event.extend(event); + } + + + Object.extend(Event, Event.Methods); + + Object.extend(Event, { + fire: fire, + observe: observe, + stopObserving: stopObserving + }); + + Element.addMethods({ + fire: fire, + + observe: observe, + + stopObserving: stopObserving + }); + + Object.extend(document, { + fire: fire.methodize(), + + observe: observe.methodize(), + + stopObserving: stopObserving.methodize(), + + loaded: false + }); + + if (window.Event) Object.extend(window.Event, Event); + else window.Event = Event; +})(); + +(function() { + /* Support for the DOMContentLoaded event is based on work by Dan Webb, + Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */ + + var timer; + + function fireContentLoadedEvent() { + if (document.loaded) return; + if (timer) window.clearTimeout(timer); + document.loaded = true; + document.fire('dom:loaded'); + } + + function checkReadyState() { + if (document.readyState === 'complete') { + document.stopObserving('readystatechange', checkReadyState); + fireContentLoadedEvent(); + } + } + + function pollDoScroll() { + try { document.documentElement.doScroll('left'); } + catch(e) { + timer = pollDoScroll.defer(); + return; + } + fireContentLoadedEvent(); + } + + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false); + } else { + document.observe('readystatechange', checkReadyState); + if (window == top) + timer = pollDoScroll.defer(); + } + + Event.observe(window, 'load', fireContentLoadedEvent); +})(); + +Element.addMethods(); + +/*------------------------------- DEPRECATED -------------------------------*/ + +Hash.toQueryString = Object.toQueryString; + +var Toggle = { display: Element.toggle }; + +Element.Methods.childOf = Element.Methods.descendantOf; + +var Insertion = { + Before: function(element, content) { + return Element.insert(element, {before:content}); + }, + + Top: function(element, content) { + return Element.insert(element, {top:content}); + }, + + Bottom: function(element, content) { + return Element.insert(element, {bottom:content}); + }, + + After: function(element, content) { + return Element.insert(element, {after:content}); + } +}; + +var $continue = new Error('"throw $continue" is deprecated, use "return" instead'); + +var Position = { + includeScrollOffsets: false, + + prepare: function() { + this.deltaX = window.pageXOffset + || document.documentElement.scrollLeft + || document.body.scrollLeft + || 0; + this.deltaY = window.pageYOffset + || document.documentElement.scrollTop + || document.body.scrollTop + || 0; + }, + + within: function(element, x, y) { + if (this.includeScrollOffsets) + return this.withinIncludingScrolloffsets(element, x, y); + this.xcomp = x; + this.ycomp = y; + this.offset = Element.cumulativeOffset(element); + + return (y >= this.offset[1] && + y < this.offset[1] + element.offsetHeight && + x >= this.offset[0] && + x < this.offset[0] + element.offsetWidth); + }, + + withinIncludingScrolloffsets: function(element, x, y) { + var offsetcache = Element.cumulativeScrollOffset(element); + + this.xcomp = x + offsetcache[0] - this.deltaX; + this.ycomp = y + offsetcache[1] - this.deltaY; + this.offset = Element.cumulativeOffset(element); + + return (this.ycomp >= this.offset[1] && + this.ycomp < this.offset[1] + element.offsetHeight && + this.xcomp >= this.offset[0] && + this.xcomp < this.offset[0] + element.offsetWidth); + }, + + overlap: function(mode, element) { + if (!mode) return 0; + if (mode == 'vertical') + return ((this.offset[1] + element.offsetHeight) - this.ycomp) / + element.offsetHeight; + if (mode == 'horizontal') + return ((this.offset[0] + element.offsetWidth) - this.xcomp) / + element.offsetWidth; + }, + + + cumulativeOffset: Element.Methods.cumulativeOffset, + + positionedOffset: Element.Methods.positionedOffset, + + absolutize: function(element) { + Position.prepare(); + return Element.absolutize(element); + }, + + relativize: function(element) { + Position.prepare(); + return Element.relativize(element); + }, + + realOffset: Element.Methods.cumulativeScrollOffset, + + offsetParent: Element.Methods.getOffsetParent, + + page: Element.Methods.viewportOffset, + + clone: function(source, target, options) { + options = options || { }; + return Element.clonePosition(target, source, options); + } +}; + +/*--------------------------------------------------------------------------*/ + +if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){ + function iter(name) { + return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]"; + } + + instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ? + function(element, className) { + className = className.toString().strip(); + var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className); + return cond ? document._getElementsByXPath('.//*' + cond, element) : []; + } : function(element, className) { + className = className.toString().strip(); + var elements = [], classNames = (/\s/.test(className) ? $w(className) : null); + if (!classNames && !className) return elements; + + var nodes = $(element).getElementsByTagName('*'); + className = ' ' + className + ' '; + + for (var i = 0, child, cn; child = nodes[i]; i++) { + if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) || + (classNames && classNames.all(function(name) { + return !name.toString().blank() && cn.include(' ' + name + ' '); + })))) + elements.push(Element.extend(child)); + } + return elements; + }; + + return function(className, parentElement) { + return $(parentElement || document.body).getElementsByClassName(className); + }; +}(Element.Methods); + +/*--------------------------------------------------------------------------*/ + +Element.ClassNames = Class.create(); +Element.ClassNames.prototype = { + initialize: function(element) { + this.element = $(element); + }, + + _each: function(iterator) { + this.element.className.split(/\s+/).select(function(name) { + return name.length > 0; + })._each(iterator); + }, + + set: function(className) { + this.element.className = className; + }, + + add: function(classNameToAdd) { + if (this.include(classNameToAdd)) return; + this.set($A(this).concat(classNameToAdd).join(' ')); + }, + + remove: function(classNameToRemove) { + if (!this.include(classNameToRemove)) return; + this.set($A(this).without(classNameToRemove).join(' ')); + }, + + toString: function() { + return $A(this).join(' '); + } +}; + +Object.extend(Element.ClassNames.prototype, Enumerable); + +/*--------------------------------------------------------------------------*/ diff --git a/expectations/selenium_expectations/selenium_test_page.html b/expectations/selenium_expectations/selenium_test_page.html index 304d042..69ee085 100644 --- a/expectations/selenium_expectations/selenium_test_page.html +++ b/expectations/selenium_expectations/selenium_test_page.html @@ -1,25 +1,58 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> +<script type="text/javascript" src="jquery-1.4.2.min.js"></script> +<script type="text/javascript" src="jquery.sleep.js" ></script> +<script type="text/javascript" src="prototype.js"></script> + +<script type="text/javascript"> +jQuery(document).ready(function() { + jQuery('#test_jQuery_link').click(function() + { + jQuery.active = 1; + jQuery.sleep(3, function() + { + jQuery.active = 0; + }); + } + ); + + jQuery('#test_Prototype_link').click(function() + { + Ajax.activeRequestCount = 1; + jQuery.sleep(3, function() + { + alert('Prototype'); + Ajax.activeRequestCount = 0; + }); + } +); + +}); +</script> </head> <body> <span id="test_span">Text</span> <br /> <label for='test_checkbox'>Checkbox</label><input name="test_checkbox" type="checkbox"/> <br /> <label for='test_radio'>Radio</label><input name="test_radio" type="radio"/> <br /> <label for=test_select">Select</label> <select id="test_select"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> <br /> <label for="test_textfield">Text field</label> <input type="text" /> +<br /> +<br /> +<a id="test_jQuery_link" href="#" >jQuery ajax Link</a> +<a id="test_Prototype_link" href="#" >Prototype ajax Link</a> </body> </html> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumActions.php b/src/selenium_helper/SeleniumActions.php index 5420492..4718175 100644 --- a/src/selenium_helper/SeleniumActions.php +++ b/src/selenium_helper/SeleniumActions.php @@ -1,96 +1,112 @@ <?php class SeleniumActions { private $__seleniumExecutionContext; - + public function __construct($seleniumExecutionContext) { - $this->__seleniumExecutionContext= $seleniumExecutionContext; + $this->__seleniumExecutionContext= $seleniumExecutionContext; } - + private function __getLastVisitedLocation() { return $this->__seleniumExecutionContext->getLastVisitedLocation(); } - + private function __getSelenium() { return $this->__seleniumExecutionContext->getSelenium(); } - + private function __setLastVisitedLocation($location) { $this->__seleniumExecutionContext->setLastVisitedLocation($location); } private function __resetLastVisitedLocation() { $this->__seleniumExecutionContext->resetLastVisitedLocation(); } - + public function goesTo($url) { $this->__getSelenium()->open($url); } - + public function fillsOut($text_field_locator) { $this->__setLastVisitedLocation($text_field_locator); } - + public function with($value) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to type... Please specify where to type."); $this->__getSelenium()->type($this->__getLastVisitedLocation(), $value); $this->__resetLastVisitedLocation(); } - + public function clicks($locator) { $this->__getSelenium()->click($locator); } - + public function and_then() { } - + public function waitsForPageToLoad() { $this->__getSelenium()->waitForPageToLoad(30000); } - + public function drags($objects_locator) { $this->__setLastVisitedLocation($objects_locator); } - + public function dropsOn($destinations_locator) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to drop... Please specify where to drop the object."); $this->__getSelenium()->dragAndDropToObject($this->__getLastVisitedLocation(),$destinations_locator); } - + public function checks($checkbox_or_radio_button_locator) { $this->clicks($checkbox_or_radio_button_locator); } - + public function selects($value) { - $this->__setLastVisitedLocation($value); + $this->__setLastVisitedLocation($value); } - + public function from($dropdown_list_locator) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to pick from... Please specify where to find the selection."); $this->__getSelenium()->select($dropdown_list_locator,'label='.$this->__getLastVisitedLocation()); - $this->__resetLastVisitedLocation(); + $this->__resetLastVisitedLocation(); } - - - + + public function waitsForAjax($timeout) + { + $javascriptLibrary = $this->__seleniumExecutionContext->getJavascriptLibrary(); + + $waitForAjaxCondition = call_user_func(array($this,'get'.$javascriptLibrary.'WaitForAjaxCondition')); + $this->__getSelenium()->waitForCondition($waitForAjaxCondition, $timeout); + } + + public function getjQueryWaitForAjaxCondition() + { + return "selenium.browserbot.getCurrentWindow().jQuery.active == 0"; + } + + public function getPrototypeWaitForAjaxCondition() + { + return "selenium.browserbot.getCurrentWindow().Ajax.activeRequestCount == 0"; + } + } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumDrivenUser.php b/src/selenium_helper/SeleniumDrivenUser.php index 745f78d..c08079c 100644 --- a/src/selenium_helper/SeleniumDrivenUser.php +++ b/src/selenium_helper/SeleniumDrivenUser.php @@ -1,49 +1,50 @@ <?php - + require_once 'Testing/Selenium.php'; + require_once dirname(__FILE__).'/../Expectations.php'; require_once dirname(__FILE__).'/SeleniumActions.php'; require_once dirname(__FILE__).'/SeleniumExpectations.php'; - + class SeleniumDrivenUser { - + private $__seleniumExecutionContext; private $__seleniumActions; private $__seleniumExpectations; - + public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext = $seleniumExecutionContext; $this->__seleniumActions = new SeleniumActions($this->__seleniumExecutionContext); $this->__seleniumExpectations = new SeleniumExpectations($this->__seleniumExecutionContext); $this->__seleniumExecutionContext->initialize(); } - + public function destroy() { $this->__seleniumExecutionContext->destroy(); } - + function __call($method_name, $args) { if(method_exists($this->__seleniumActions, $method_name)) { call_user_func_array( array($this->__seleniumActions, $method_name), $args); return $this; } else if(method_exists(SeleniumExpectations, $method_name)) { call_user_func_array( array($this->__seleniumExpectations, $method_name), $args); return $this; } else { - throw new Exception('Unknown method '.$method_name."called on ".get_class($this)." instance."); + throw new Exception('Unknown method '.$method_name."called on ".get_class($this)." instance."); } } - - + + } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExecutionContext.php b/src/selenium_helper/SeleniumExecutionContext.php index 6609927..8e92ae1 100644 --- a/src/selenium_helper/SeleniumExecutionContext.php +++ b/src/selenium_helper/SeleniumExecutionContext.php @@ -1,75 +1,84 @@ <?php + require_once 'src/selenium_helper/SeleniumExtendedDriver.php'; + class SeleniumExecutionContext { private $__browser; private $__website; private $__selenium; private $__isInitialized; private $__lastVisitedLocation; - - public function __construct($browser, $website) + private $__javascript_library; + + public function __construct($browser, $website, $javascript_library) { $this->__browser = $browser; - $this->__website = $website; - $this->__selenium = new Testing_Selenium($browser, $website); + $this->__website = $website; + $this->__javascript_library = $javascript_library; + $this->__selenium = new SeleniumExtendedDriver($browser, $website); $this->__isInitialized = false; $this->resetLastVisitedLocation(); } - + public function getBrowser() { return $this->__browser; } - + public function getWebSite() { return $this->__website; } - + + public function getJavascriptLibrary() + { + return $this->__javascript_library; + } + public function getSelenium() { return $this->__selenium; } - + public function setLastVisitedLocation($location) { - $this->__lastVisitedLocation = $location; + $this->__lastVisitedLocation = $location; } - + public function getLastVisitedLocation() { return $this->__lastVisitedLocation; } - + public function resetLastVisitedLocation() { - $this->__lastVisitedLocation = null; + $this->__lastVisitedLocation = null; } - + public function initialize() { if(!$this->__isInitialized) $this->__startSelenium(); } - + public function destroy() { if($this->__isInitialized) $this->__stopSelenium(); } - + private function __startSelenium() { $this->__selenium->start(); $this->__isInitialized = true; } - + private function __stopSelenium() { $this->__selenium->close(); $this->__selenium->stop(); } - + } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExtendedDriver.php b/src/selenium_helper/SeleniumExtendedDriver.php new file mode 100644 index 0000000..c05d681 --- /dev/null +++ b/src/selenium_helper/SeleniumExtendedDriver.php @@ -0,0 +1,17 @@ +<?php + require_once 'Testing/Selenium.php'; + + class SeleniumTimedOutException extends Exception{} + + class SeleniumExtendedDriver extends Testing_Selenium + { + public function waitForCondition($script,$timeout) + { + $result = $this->doCommand("waitForCondition", array($script, $timeout)); + + if(strpos($result,"Timed out") !== false){ + throw new SeleniumTimedOutException("Selenium waitForCondition has timed out"); + } + } + } +?> \ No newline at end of file
xto/SUTA
4d4ce73eefad67fe59e17702051e90e2a1c5626d
adding missing static attribute after refactoring of seleniumDrivenUserExpections
diff --git a/Testing/Selenium.php b/Testing/Selenium.php new file mode 100644 index 0000000..d101bfd --- /dev/null +++ b/Testing/Selenium.php @@ -0,0 +1,2755 @@ +<?php +/** Copyright 2006 ThoughtWorks, Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ----------------- + * This file has been automatically generated via XSL + * ----------------- + * + * + * + * @category Testing + * @package Selenium + * @author Shin Ohno <ganchiku at gmail dot com> + * @author Bjoern Schotte <schotte at mayflower dot de> + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0 + * @version @package_version@ + * @see http://www.openqa.org/selenium-rc/ + * @since 0.1 + */ + +/** + * Selenium exception class + */ +require_once 'Testing/Selenium/Exception.php'; + +/** + * Defines an object that runs Selenium commands. + * + * + * <p> + * <b>Element Locators</b> + * </p><p> + * + * Element Locators tell Selenium which HTML element a command refers to. + * The format of a locator is: + * </p><p> + * + * <i>locatorType</i><b>=</b><i>argument</i> + * </p> + * <p> + * + * We support the following strategies for locating elements: + * + * </p> + * <ul> + * + * <li> + * <b>identifier</b>=<i>id</i>: + * Select the element with the specified @id attribute. If no match is + * found, select the first element whose @name attribute is <i>id</i>. + * (This is normally the default; see below.) + * </li> + * <li> + * <b>id</b>=<i>id</i>: + * Select the element with the specified @id attribute. + * </li> + * <li> + * <b>name</b>=<i>name</i>: + * Select the first element with the specified @name attribute. + * + * <ul> + * + * <li> + * username + * </li> + * <li> + * name=username + * </li> + * </ul> +<p> + * The name may optionally be followed by one or more <i>element-filters</i>, separated from the name by whitespace. If the <i>filterType</i> is not specified, <b>value</b> is assumed. + * </p> + * <ul> + * + * <li> + * name=flavour value=chocolate + * </li> + * </ul> + * </li> + * <li> + * <b>dom</b>=<i>javascriptExpression</i>: + * + * Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object + * Model using JavaScript. Note that you must not return a value in this string; simply make it the last expression in the block. + * + * <ul> + * + * <li> + * dom=document.forms['myForm'].myDropdown + * </li> + * <li> + * dom=document.images[56] + * </li> + * <li> + * dom=function foo() { return document.links[1]; }; foo(); + * </li> + * </ul> + * </li> + * <li> + * <b>xpath</b>=<i>xpathExpression</i>: + * Locate an element using an XPath expression. + * + * <ul> + * + * <li> + * xpath=//img[@alt='The image alt text'] + * </li> + * <li> + * xpath=//table[@id='table1']//tr[4]/td[2] + * </li> + * <li> + * xpath=//a[contains(@href,'#id1')] + * </li> + * <li> + * xpath=//a[contains(@href,'#id1')]/@class + * </li> + * <li> + * xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td + * </li> + * <li> + * xpath=//input[@name='name2' and @value='yes'] + * </li> + * <li> + * xpath=//*[text()="right"] + * </li> + * </ul> + * </li> + * <li> + * <b>link</b>=<i>textPattern</i>: + * Select the link (anchor) element which contains text matching the + * specified <i>pattern</i>. + * + * <ul> + * + * <li> + * link=The link text + * </li> + * </ul> + * </li> + * <li> + * <b>css</b>=<i>cssSelectorSyntax</i>: + * Select the element using css selectors. Please refer to CSS2 selectors, CSS3 selectors for more information. You can also check the TestCssLocators test in the selenium test suite for an example of usage, which is included in the downloaded selenium core package. + * + * <ul> + * + * <li> + * css=a[href="#id3"] + * </li> + * <li> + * css=span#firstChild + span + * </li> + * </ul> +<p> + * Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after). + * </p> + * </li> + * <li> + * <b>ui</b>=<i>uiSpecifierString</i>: + * Locate an element by resolving the UI specifier string to another locator, and evaluating it. See the Selenium UI-Element Reference for more details. + * + * <ul> + * + * <li> + * ui=loginPages::loginButton() + * </li> + * <li> + * ui=settingsPages::toggle(label=Hide Email) + * </li> + * <li> + * ui=forumPages::postBody(index=2)//a[2] + * </li> + * </ul> + * </li> + * </ul><p> + * + * Without an explicit locator prefix, Selenium uses the following default + * strategies: + * + * </p> + * <ul> + * + * <li> + * <b>dom</b>, for locators starting with "document." + * </li> + * <li> + * <b>xpath</b>, for locators starting with "//" + * </li> + * <li> + * <b>identifier</b>, otherwise + * </li> + * </ul> + * <p> + * <b>Element Filters</b> + * </p><p> + * + * <p> + * Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator. + * </p> +<p> + * Filters look much like locators, ie. + * </p> +<p> + * + * <i>filterType</i><b>=</b><i>argument</i> + * </p> + * <p> + * Supported element-filters are: + * </p> +<p> + * <b>value=</b><i>valuePattern</i> + * </p> +<p> + * + * + * Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons. + * </p> + * <p> + * <b>index=</b><i>index</i> + * </p> +<p> + * + * + * Selects a single element based on its position in the list (offset from zero). + * </p> + * + * </p> + * + * <p> + * <b>String-match Patterns</b> + * </p><p> + * + * Various Pattern syntaxes are available for matching string values: + * + * </p> + * <ul> + * + * <li> + * <b>glob:</b><i>pattern</i>: + * Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a + * kind of limited regular-expression syntax typically used in command-line + * shells. In a glob pattern, "*" represents any sequence of characters, and "?" + * represents any single character. Glob patterns match against the entire + * string. + * </li> + * <li> + * <b>regexp:</b><i>regexp</i>: + * Match a string using a regular-expression. The full power of JavaScript + * regular-expressions is available. + * </li> + * <li> + * <b>regexpi:</b><i>regexpi</i>: + * Match a string using a case-insensitive regular-expression. + * </li> + * <li> + * <b>exact:</b><i>string</i>: + * + * Match a string exactly, verbatim, without any of that fancy wildcard + * stuff. + * </li> + * </ul><p> + * + * If no pattern prefix is specified, Selenium assumes that it's a "glob" + * pattern. + * + * </p><p> + * + * For commands that return multiple values (such as verifySelectOptions), + * the string being matched is a comma-separated list of the return values, + * where both commas and backslashes in the values are backslash-escaped. + * When providing a pattern, the optional matching syntax (i.e. glob, + * regexp, etc.) is specified once, as usual, at the beginning of the + * pattern. + * + * </p> + * + * @package Selenium + * @author Shin Ohno <ganchiku at gmail dot com> + * @author Bjoern Schotte <schotte at mayflower dot de> + */ +class Testing_Selenium +{ + /** + * @var string + * @access private + */ + private $browser; + + /** + * @var string + * @access private + */ + private $browserUrl; + + /** + * @var string + * @access private + */ + private $host; + + /** + * @var int + * @access private + */ + private $port; + + /** + * @var string + * @access private + */ + private $sessionId; + + /** + * @var string + * @access private + */ + private $timeout; + + /** + * Constructor + * + * @param string $browser + * @param string $browserUrl + * @param string $host + * @param int $port + * @param int $timeout + * @access public + * @throws Testing_Selenium_Exception + */ + public function __construct($browser, $browserUrl, $host = 'localhost', $port = 4444, $timeout = 30000) + { + $this->browser = $browser; + $this->browserUrl = $browserUrl; + $this->host = $host; + $this->port = $port; + $this->timeout = $timeout; + } + + /** + * Run the browser and set session id. + * + * @access public + * @return void + */ + public function start() + { + $this->sessionId = $this->getString("getNewBrowserSession", array($this->browser, $this->browserUrl)); + return $this->sessionId; + } + + /** + * Close the browser and set session id null + * + * @access public + * @return void + */ + public function stop() + { + $this->doCommand("testComplete"); + $this->sessionId = null; + } + + /** + * Clicks on a link, button, checkbox or radio button. If the click action + * causes a new page to load (like a link usually does), call + * waitForPageToLoad. + * + * @access public + * @param string $locator an element locator + */ + public function click($locator) + { + $this->doCommand("click", array($locator)); + } + + + /** + * Double clicks on a link, button, checkbox or radio button. If the double click action + * causes a new page to load (like a link usually does), call + * waitForPageToLoad. + * + * @access public + * @param string $locator an element locator + */ + public function doubleClick($locator) + { + $this->doCommand("doubleClick", array($locator)); + } + + + /** + * Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element). + * + * @access public + * @param string $locator an element locator + */ + public function contextMenu($locator) + { + $this->doCommand("contextMenu", array($locator)); + } + + + /** + * Clicks on a link, button, checkbox or radio button. If the click action + * causes a new page to load (like a link usually does), call + * waitForPageToLoad. + * + * @access public + * @param string $locator an element locator + * @param string $coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. + */ + public function clickAt($locator, $coordString) + { + $this->doCommand("clickAt", array($locator, $coordString)); + } + + + /** + * Doubleclicks on a link, button, checkbox or radio button. If the action + * causes a new page to load (like a link usually does), call + * waitForPageToLoad. + * + * @access public + * @param string $locator an element locator + * @param string $coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. + */ + public function doubleClickAt($locator, $coordString) + { + $this->doCommand("doubleClickAt", array($locator, $coordString)); + } + + + /** + * Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element). + * + * @access public + * @param string $locator an element locator + * @param string $coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. + */ + public function contextMenuAt($locator, $coordString) + { + $this->doCommand("contextMenuAt", array($locator, $coordString)); + } + + + /** + * Explicitly simulate an event, to trigger the corresponding "on<i>event</i>" + * handler. + * + * @access public + * @param string $locator an element locator + * @param string $eventName the event name, e.g. "focus" or "blur" + */ + public function fireEvent($locator, $eventName) + { + $this->doCommand("fireEvent", array($locator, $eventName)); + } + + + /** + * Move the focus to the specified element; for example, if the element is an input field, move the cursor to that field. + * + * @access public + * @param string $locator an element locator + */ + public function focus($locator) + { + $this->doCommand("focus", array($locator)); + } + + + /** + * Simulates a user pressing and releasing a key. + * + * @access public + * @param string $locator an element locator + * @param string $keySequence Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". + */ + public function keyPress($locator, $keySequence) + { + $this->doCommand("keyPress", array($locator, $keySequence)); + } + + + /** + * Press the shift key and hold it down until doShiftUp() is called or a new page is loaded. + * + * @access public + */ + public function shiftKeyDown() + { + $this->doCommand("shiftKeyDown", array()); + } + + + /** + * Release the shift key. + * + * @access public + */ + public function shiftKeyUp() + { + $this->doCommand("shiftKeyUp", array()); + } + + + /** + * Press the meta key and hold it down until doMetaUp() is called or a new page is loaded. + * + * @access public + */ + public function metaKeyDown() + { + $this->doCommand("metaKeyDown", array()); + } + + + /** + * Release the meta key. + * + * @access public + */ + public function metaKeyUp() + { + $this->doCommand("metaKeyUp", array()); + } + + + /** + * Press the alt key and hold it down until doAltUp() is called or a new page is loaded. + * + * @access public + */ + public function altKeyDown() + { + $this->doCommand("altKeyDown", array()); + } + + + /** + * Release the alt key. + * + * @access public + */ + public function altKeyUp() + { + $this->doCommand("altKeyUp", array()); + } + + + /** + * Press the control key and hold it down until doControlUp() is called or a new page is loaded. + * + * @access public + */ + public function controlKeyDown() + { + $this->doCommand("controlKeyDown", array()); + } + + + /** + * Release the control key. + * + * @access public + */ + public function controlKeyUp() + { + $this->doCommand("controlKeyUp", array()); + } + + + /** + * Simulates a user pressing a key (without releasing it yet). + * + * @access public + * @param string $locator an element locator + * @param string $keySequence Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". + */ + public function keyDown($locator, $keySequence) + { + $this->doCommand("keyDown", array($locator, $keySequence)); + } + + + /** + * Simulates a user releasing a key. + * + * @access public + * @param string $locator an element locator + * @param string $keySequence Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". + */ + public function keyUp($locator, $keySequence) + { + $this->doCommand("keyUp", array($locator, $keySequence)); + } + + + /** + * Simulates a user hovering a mouse over the specified element. + * + * @access public + * @param string $locator an element locator + */ + public function mouseOver($locator) + { + $this->doCommand("mouseOver", array($locator)); + } + + + /** + * Simulates a user moving the mouse pointer away from the specified element. + * + * @access public + * @param string $locator an element locator + */ + public function mouseOut($locator) + { + $this->doCommand("mouseOut", array($locator)); + } + + + /** + * Simulates a user pressing the left mouse button (without releasing it yet) on + * the specified element. + * + * @access public + * @param string $locator an element locator + */ + public function mouseDown($locator) + { + $this->doCommand("mouseDown", array($locator)); + } + + + /** + * Simulates a user pressing the right mouse button (without releasing it yet) on + * the specified element. + * + * @access public + * @param string $locator an element locator + */ + public function mouseDownRight($locator) + { + $this->doCommand("mouseDownRight", array($locator)); + } + + + /** + * Simulates a user pressing the left mouse button (without releasing it yet) at + * the specified location. + * + * @access public + * @param string $locator an element locator + * @param string $coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. + */ + public function mouseDownAt($locator, $coordString) + { + $this->doCommand("mouseDownAt", array($locator, $coordString)); + } + + + /** + * Simulates a user pressing the right mouse button (without releasing it yet) at + * the specified location. + * + * @access public + * @param string $locator an element locator + * @param string $coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. + */ + public function mouseDownRightAt($locator, $coordString) + { + $this->doCommand("mouseDownRightAt", array($locator, $coordString)); + } + + + /** + * Simulates the event that occurs when the user releases the mouse button (i.e., stops + * holding the button down) on the specified element. + * + * @access public + * @param string $locator an element locator + */ + public function mouseUp($locator) + { + $this->doCommand("mouseUp", array($locator)); + } + + + /** + * Simulates the event that occurs when the user releases the right mouse button (i.e., stops + * holding the button down) on the specified element. + * + * @access public + * @param string $locator an element locator + */ + public function mouseUpRight($locator) + { + $this->doCommand("mouseUpRight", array($locator)); + } + + + /** + * Simulates the event that occurs when the user releases the mouse button (i.e., stops + * holding the button down) at the specified location. + * + * @access public + * @param string $locator an element locator + * @param string $coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. + */ + public function mouseUpAt($locator, $coordString) + { + $this->doCommand("mouseUpAt", array($locator, $coordString)); + } + + + /** + * Simulates the event that occurs when the user releases the right mouse button (i.e., stops + * holding the button down) at the specified location. + * + * @access public + * @param string $locator an element locator + * @param string $coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. + */ + public function mouseUpRightAt($locator, $coordString) + { + $this->doCommand("mouseUpRightAt", array($locator, $coordString)); + } + + + /** + * Simulates a user pressing the mouse button (without releasing it yet) on + * the specified element. + * + * @access public + * @param string $locator an element locator + */ + public function mouseMove($locator) + { + $this->doCommand("mouseMove", array($locator)); + } + + + /** + * Simulates a user pressing the mouse button (without releasing it yet) on + * the specified element. + * + * @access public + * @param string $locator an element locator + * @param string $coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. + */ + public function mouseMoveAt($locator, $coordString) + { + $this->doCommand("mouseMoveAt", array($locator, $coordString)); + } + + + /** + * Sets the value of an input field, as though you typed it in. + * + * <p> + * Can also be used to set the value of combo boxes, check boxes, etc. In these cases, + * value should be the value of the option selected, not the visible text. + * </p> + * + * @access public + * @param string $locator an element locator + * @param string $value the value to type + */ + public function type($locator, $value) + { + $this->doCommand("type", array($locator, $value)); + } + + + /** + * Simulates keystroke events on the specified element, as though you typed the value key-by-key. + * + * <p> + * This is a convenience method for calling keyDown, keyUp, keyPress for every character in the specified string; + * this is useful for dynamic UI widgets (like auto-completing combo boxes) that require explicit key events. + * </p><p> + * Unlike the simple "type" command, which forces the specified value into the page directly, this command + * may or may not have any visible effect, even in cases where typing keys would normally have a visible effect. + * For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in + * the field. + * </p><p> + * In some cases, you may need to use the simple "type" command to set the value of the field and then the "typeKeys" command to + * send the keystroke events corresponding to what you just typed. + * </p> + * + * @access public + * @param string $locator an element locator + * @param string $value the value to type + */ + public function typeKeys($locator, $value) + { + $this->doCommand("typeKeys", array($locator, $value)); + } + + + /** + * Set execution speed (i.e., set the millisecond length of a delay which will follow each selenium operation). By default, there is no such delay, i.e., + * the delay is 0 milliseconds. + * + * @access public + * @param string $value the number of milliseconds to pause after operation + */ + public function setSpeed($value) + { + $this->doCommand("setSpeed", array($value)); + } + + + /** + * Get execution speed (i.e., get the millisecond length of the delay following each selenium operation). By default, there is no such delay, i.e., + * the delay is 0 milliseconds. + * + * See also setSpeed. + * + * @access public + * @return string the execution speed in milliseconds. + */ + public function getSpeed() + { + return $this->getString("getSpeed", array()); + } + + + /** + * Check a toggle-button (checkbox/radio) + * + * @access public + * @param string $locator an element locator + */ + public function check($locator) + { + $this->doCommand("check", array($locator)); + } + + + /** + * Uncheck a toggle-button (checkbox/radio) + * + * @access public + * @param string $locator an element locator + */ + public function uncheck($locator) + { + $this->doCommand("uncheck", array($locator)); + } + + + /** + * Select an option from a drop-down using an option locator. + * + * <p> + * + * Option locators provide different ways of specifying options of an HTML + * Select element (e.g. for selecting a specific option, or for asserting + * that the selected option satisfies a specification). There are several + * forms of Select Option Locator. + * + * </p> + * <ul> + * + * <li> + * <b>label</b>=<i>labelPattern</i>: + * matches options based on their labels, i.e. the visible text. (This + * is the default.) + * + * <ul> + * + * <li> + * label=regexp:^[Oo]ther + * </li> + * </ul> + * </li> + * <li> + * <b>value</b>=<i>valuePattern</i>: + * matches options based on their values. + * + * <ul> + * + * <li> + * value=other + * </li> + * </ul> + * </li> + * <li> + * <b>id</b>=<i>id</i>: + * + * matches options based on their ids. + * + * <ul> + * + * <li> + * id=option1 + * </li> + * </ul> + * </li> + * <li> + * <b>index</b>=<i>index</i>: + * matches an option based on its index (offset from zero). + * + * <ul> + * + * <li> + * index=2 + * </li> + * </ul> + * </li> + * </ul><p> + * + * If no option locator prefix is provided, the default behaviour is to match on <b>label</b>. + * + * </p> + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @param string $optionLocator an option locator (a label by default) + */ + public function select($selectLocator, $optionLocator) + { + $this->doCommand("select", array($selectLocator, $optionLocator)); + } + + + /** + * Add a selection to the set of selected options in a multi-select element using an option locator. + * + * @see #doSelect for details of option locators + * + * @access public + * @param string $locator an element locator identifying a multi-select box + * @param string $optionLocator an option locator (a label by default) + */ + public function addSelection($locator, $optionLocator) + { + $this->doCommand("addSelection", array($locator, $optionLocator)); + } + + + /** + * Remove a selection from the set of selected options in a multi-select element using an option locator. + * + * @see #doSelect for details of option locators + * + * @access public + * @param string $locator an element locator identifying a multi-select box + * @param string $optionLocator an option locator (a label by default) + */ + public function removeSelection($locator, $optionLocator) + { + $this->doCommand("removeSelection", array($locator, $optionLocator)); + } + + + /** + * Unselects all of the selected options in a multi-select element. + * + * @access public + * @param string $locator an element locator identifying a multi-select box + */ + public function removeAllSelections($locator) + { + $this->doCommand("removeAllSelections", array($locator)); + } + + + /** + * Submit the specified form. This is particularly useful for forms without + * submit buttons, e.g. single-input "Search" forms. + * + * @access public + * @param string $formLocator an element locator for the form you want to submit + */ + public function submit($formLocator) + { + $this->doCommand("submit", array($formLocator)); + } + + + /** + * Opens an URL in the test frame. This accepts both relative and absolute + * URLs. + * + * The "open" command waits for the page to load before proceeding, + * ie. the "AndWait" suffix is implicit. + * + * <i>Note</i>: The URL must be on the same domain as the runner HTML + * due to security restrictions in the browser (Same Origin Policy). If you + * need to open an URL on another domain, use the Selenium Server to start a + * new browser session on that domain. + * + * @access public + * @param string $url the URL to open; may be relative or absolute + */ + public function open($url) + { + $this->doCommand("open", array($url)); + } + + + /** + * Opens a popup window (if a window with that ID isn't already open). + * After opening the window, you'll need to select it using the selectWindow + * command. + * + * <p> + * This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example). + * In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using + * an empty (blank) url, like this: openWindow("", "myFunnyWindow"). + * </p> + * + * @access public + * @param string $url the URL to open, which can be blank + * @param string $windowID the JavaScript window ID of the window to select + */ + public function openWindow($url, $windowID) + { + $this->doCommand("openWindow", array($url, $windowID)); + } + + + /** + * Selects a popup window using a window locator; once a popup window has been selected, all + * commands go to that window. To select the main window again, use null + * as the target. + * + * <p> + * + * + * Window locators provide different ways of specifying the window object: + * by title, by internal JavaScript "name," or by JavaScript variable. + * + * </p> + * <ul> + * + * <li> + * <b>title</b>=<i>My Special Window</i>: + * Finds the window using the text that appears in the title bar. Be careful; + * two windows can share the same title. If that happens, this locator will + * just pick one. + * + * </li> + * <li> + * <b>name</b>=<i>myWindow</i>: + * Finds the window using its internal JavaScript "name" property. This is the second + * parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures, replaceFlag) + * (which Selenium intercepts). + * + * </li> + * <li> + * <b>var</b>=<i>variableName</i>: + * Some pop-up windows are unnamed (anonymous), but are associated with a JavaScript variable name in the current + * application window, e.g. "window.foo = window.open(url);". In those cases, you can open the window using + * "var=foo". + * + * </li> + * </ul><p> + * + * If no window locator prefix is provided, we'll try to guess what you mean like this: + * </p><p> + * 1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window instantiated by the browser). + * </p><p> + * 2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window, then it is assumed + * that this variable contains the return value from a call to the JavaScript window.open() method. + * </p><p> + * 3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names". + * </p><p> + * 4.) If <i>that</i> fails, we'll try looping over all of the known windows to try to find the appropriate "title". + * Since "title" is not necessarily unique, this may have unexpected behavior. + * </p><p> + * If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log messages + * which identify the names of windows created via window.open (and therefore intercepted by Selenium). You will see messages + * like the following for each window as it is opened: + * </p><p> + * <code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is "myNewWindow"</code> + * </p><p> + * In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example). + * (This is bug SEL-339.) In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using + * an empty (blank) url, like this: openWindow("", "myFunnyWindow"). + * </p> + * + * @access public + * @param string $windowID the JavaScript window ID of the window to select + */ + public function selectWindow($windowID) + { + $this->doCommand("selectWindow", array($windowID)); + } + + + /** + * Simplifies the process of selecting a popup window (and does not offer + * functionality beyond what <code>selectWindow()</code> already provides). + * + * <ul> + * + * <li> + * If <code>windowID</code> is either not specified, or specified as + * "null", the first non-top window is selected. The top window is the one + * that would be selected by <code>selectWindow()</code> without providing a + * <code>windowID</code> . This should not be used when more than one popup + * window is in play. + * </li> + * <li> + * Otherwise, the window will be looked up considering + * <code>windowID</code> as the following in order: 1) the "name" of the + * window, as specified to <code>window.open()</code>; 2) a javascript + * variable which is a reference to a window; and 3) the title of the + * window. This is the same ordered lookup performed by + * <code>selectWindow</code> . + * </li> + * </ul> + * + * @access public + * @param string $windowID an identifier for the popup window, which can take on a number of different meanings + */ + public function selectPopUp($windowID) + { + $this->doCommand("selectPopUp", array($windowID)); + } + + + /** + * Selects the main window. Functionally equivalent to using + * <code>selectWindow()</code> and specifying no value for + * <code>windowID</code>. + * + * @access public + */ + public function deselectPopUp() + { + $this->doCommand("deselectPopUp", array()); + } + + + /** + * Selects a frame within the current window. (You may invoke this command + * multiple times to select nested frames.) To select the parent frame, use + * "relative=parent" as a locator; to select the top frame, use "relative=top". + * You can also select a frame by its 0-based index number; select the first frame with + * "index=0", or the third frame with "index=2". + * + * <p> + * You may also use a DOM expression to identify the frame you want directly, + * like this: <code>dom=frames["main"].frames["subframe"]</code> + * </p> + * + * @access public + * @param string $locator an element locator identifying a frame or iframe + */ + public function selectFrame($locator) + { + $this->doCommand("selectFrame", array($locator)); + } + + + /** + * Determine whether current/locator identify the frame containing this running code. + * + * <p> + * This is useful in proxy injection mode, where this code runs in every + * browser frame and window, and sometimes the selenium server needs to identify + * the "current" frame. In this case, when the test calls selectFrame, this + * routine is called for each frame to figure out which one has been selected. + * The selected frame will return true, while all others will return false. + * </p> + * + * @access public + * @param string $currentFrameString starting frame + * @param string $target new frame (which might be relative to the current one) + * @return boolean true if the new frame is this code's window + */ + public function getWhetherThisFrameMatchFrameExpression($currentFrameString, $target) + { + return $this->getBoolean("getWhetherThisFrameMatchFrameExpression", array($currentFrameString, $target)); + } + + + /** + * Determine whether currentWindowString plus target identify the window containing this running code. + * + * <p> + * This is useful in proxy injection mode, where this code runs in every + * browser frame and window, and sometimes the selenium server needs to identify + * the "current" window. In this case, when the test calls selectWindow, this + * routine is called for each window to figure out which one has been selected. + * The selected window will return true, while all others will return false. + * </p> + * + * @access public + * @param string $currentWindowString starting window + * @param string $target new window (which might be relative to the current one, e.g., "_parent") + * @return boolean true if the new window is this code's window + */ + public function getWhetherThisWindowMatchWindowExpression($currentWindowString, $target) + { + return $this->getBoolean("getWhetherThisWindowMatchWindowExpression", array($currentWindowString, $target)); + } + + + /** + * Waits for a popup window to appear and load up. + * + * @access public + * @param string $windowID the JavaScript window "name" of the window that will appear (not the text of the title bar) If unspecified, or specified as "null", this command will wait for the first non-top window to appear (don't rely on this if you are working with multiple popups simultaneously). + * @param string $timeout a timeout in milliseconds, after which the action will return with an error. If this value is not specified, the default Selenium timeout will be used. See the setTimeout() command. + */ + public function waitForPopUp($windowID, $timeout) + { + $this->doCommand("waitForPopUp", array($windowID, $timeout)); + } + + + /** + * <p> + * + * By default, Selenium's overridden window.confirm() function will + * return true, as if the user had manually clicked OK; after running + * this command, the next call to confirm() will return false, as if + * the user had clicked Cancel. Selenium will then resume using the + * default behavior for future confirmations, automatically returning + * true (OK) unless/until you explicitly call this command for each + * confirmation. + * + * </p><p> + * + * Take note - every time a confirmation comes up, you must + * consume it with a corresponding getConfirmation, or else + * the next selenium operation will fail. + * + * </p> + * + * @access public + */ + public function chooseCancelOnNextConfirmation() + { + $this->doCommand("chooseCancelOnNextConfirmation", array()); + } + + + /** + * <p> + * + * Undo the effect of calling chooseCancelOnNextConfirmation. Note + * that Selenium's overridden window.confirm() function will normally automatically + * return true, as if the user had manually clicked OK, so you shouldn't + * need to use this command unless for some reason you need to change + * your mind prior to the next confirmation. After any confirmation, Selenium will resume using the + * default behavior for future confirmations, automatically returning + * true (OK) unless/until you explicitly call chooseCancelOnNextConfirmation for each + * confirmation. + * + * </p><p> + * + * Take note - every time a confirmation comes up, you must + * consume it with a corresponding getConfirmation, or else + * the next selenium operation will fail. + * + * </p> + * + * @access public + */ + public function chooseOkOnNextConfirmation() + { + $this->doCommand("chooseOkOnNextConfirmation", array()); + } + + + /** + * Instructs Selenium to return the specified answer string in response to + * the next JavaScript prompt [window.prompt()]. + * + * @access public + * @param string $answer the answer to give in response to the prompt pop-up + */ + public function answerOnNextPrompt($answer) + { + $this->doCommand("answerOnNextPrompt", array($answer)); + } + + + /** + * Simulates the user clicking the "back" button on their browser. + * + * @access public + */ + public function goBack() + { + $this->doCommand("goBack", array()); + } + + + /** + * Simulates the user clicking the "Refresh" button on their browser. + * + * @access public + */ + public function refresh() + { + $this->doCommand("refresh", array()); + } + + + /** + * Simulates the user clicking the "close" button in the titlebar of a popup + * window or tab. + * + * @access public + */ + public function close() + { + $this->doCommand("close", array()); + } + + + /** + * Has an alert occurred? + * + * <p> + * + * This function never throws an exception + * + * </p> + * + * @access public + * @return boolean true if there is an alert + */ + public function isAlertPresent() + { + return $this->getBoolean("isAlertPresent", array()); + } + + + /** + * Has a prompt occurred? + * + * <p> + * + * This function never throws an exception + * + * </p> + * + * @access public + * @return boolean true if there is a pending prompt + */ + public function isPromptPresent() + { + return $this->getBoolean("isPromptPresent", array()); + } + + + /** + * Has confirm() been called? + * + * <p> + * + * This function never throws an exception + * + * </p> + * + * @access public + * @return boolean true if there is a pending confirmation + */ + public function isConfirmationPresent() + { + return $this->getBoolean("isConfirmationPresent", array()); + } + + + /** + * Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts. + * + * <p> + * Getting an alert has the same effect as manually clicking OK. If an + * alert is generated but you do not consume it with getAlert, the next Selenium action + * will fail. + * </p><p> + * Under Selenium, JavaScript alerts will NOT pop up a visible alert + * dialog. + * </p><p> + * Selenium does NOT support JavaScript alerts that are generated in a + * page's onload() event handler. In this case a visible dialog WILL be + * generated and Selenium will hang until someone manually clicks OK. + * </p> + * + * @access public + * @return string The message of the most recent JavaScript alert + */ + public function getAlert() + { + return $this->getString("getAlert", array()); + } + + + /** + * Retrieves the message of a JavaScript confirmation dialog generated during + * the previous action. + * + * <p> + * + * By default, the confirm function will return true, having the same effect + * as manually clicking OK. This can be changed by prior execution of the + * chooseCancelOnNextConfirmation command. + * + * </p><p> + * + * If an confirmation is generated but you do not consume it with getConfirmation, + * the next Selenium action will fail. + * + * </p><p> + * + * NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible + * dialog. + * + * </p><p> + * + * NOTE: Selenium does NOT support JavaScript confirmations that are + * generated in a page's onload() event handler. In this case a visible + * dialog WILL be generated and Selenium will hang until you manually click + * OK. + * + * </p> + * + * @access public + * @return string the message of the most recent JavaScript confirmation dialog + */ + public function getConfirmation() + { + return $this->getString("getConfirmation", array()); + } + + + /** + * Retrieves the message of a JavaScript question prompt dialog generated during + * the previous action. + * + * <p> + * Successful handling of the prompt requires prior execution of the + * answerOnNextPrompt command. If a prompt is generated but you + * do not get/verify it, the next Selenium action will fail. + * </p><p> + * NOTE: under Selenium, JavaScript prompts will NOT pop up a visible + * dialog. + * </p><p> + * NOTE: Selenium does NOT support JavaScript prompts that are generated in a + * page's onload() event handler. In this case a visible dialog WILL be + * generated and Selenium will hang until someone manually clicks OK. + * </p> + * + * @access public + * @return string the message of the most recent JavaScript question prompt + */ + public function getPrompt() + { + return $this->getString("getPrompt", array()); + } + + + /** + * Gets the absolute URL of the current page. + * + * @access public + * @return string the absolute URL of the current page + */ + public function getLocation() + { + return $this->getString("getLocation", array()); + } + + + /** + * Gets the title of the current page. + * + * @access public + * @return string the title of the current page + */ + public function getTitle() + { + return $this->getString("getTitle", array()); + } + + + /** + * Gets the entire text of the page. + * + * @access public + * @return string the entire text of the page + */ + public function getBodyText() + { + return $this->getString("getBodyText", array()); + } + + + /** + * Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter). + * For checkbox/radio elements, the value will be "on" or "off" depending on + * whether the element is checked or not. + * + * @access public + * @param string $locator an element locator + * @return string the element value, or "on/off" for checkbox/radio elements + */ + public function getValue($locator) + { + return $this->getString("getValue", array($locator)); + } + + + /** + * Gets the text of an element. This works for any element that contains + * text. This command uses either the textContent (Mozilla-like browsers) or + * the innerText (IE-like browsers) of the element, which is the rendered + * text shown to the user. + * + * @access public + * @param string $locator an element locator + * @return string the text of the element + */ + public function getText($locator) + { + return $this->getString("getText", array($locator)); + } + + + /** + * Briefly changes the backgroundColor of the specified element yellow. Useful for debugging. + * + * @access public + * @param string $locator an element locator + */ + public function highlight($locator) + { + $this->doCommand("highlight", array($locator)); + } + + + /** + * Gets the result of evaluating the specified JavaScript snippet. The snippet may + * have multiple lines, but only the result of the last line will be returned. + * + * <p> + * Note that, by default, the snippet will run in the context of the "selenium" + * object itself, so <code>this</code> will refer to the Selenium object. Use <code>window</code> to + * refer to the window of your application, e.g. <code>window.document.getElementById('foo')</code> + * </p><p> + * If you need to use + * a locator to refer to a single element in your application page, you can + * use <code>this.browserbot.findElement("id=foo")</code> where "id=foo" is your locator. + * </p> + * + * @access public + * @param string $script the JavaScript snippet to run + * @return string the results of evaluating the snippet + */ + public function getEval($script) + { + return $this->getString("getEval", array($script)); + } + + + /** + * Gets whether a toggle-button (checkbox/radio) is checked. Fails if the specified element doesn't exist or isn't a toggle-button. + * + * @access public + * @param string $locator an element locator pointing to a checkbox or radio button + * @return boolean true if the checkbox is checked, false otherwise + */ + public function isChecked($locator) + { + return $this->getBoolean("isChecked", array($locator)); + } + + + /** + * Gets the text from a cell of a table. The cellAddress syntax + * tableLocator.row.column, where row and column start at 0. + * + * @access public + * @param string $tableCellAddress a cell address, e.g. "foo.1.4" + * @return string the text from the specified cell + */ + public function getTable($tableCellAddress) + { + return $this->getString("getTable", array($tableCellAddress)); + } + + + /** + * Gets all option labels (visible text) for selected options in the specified select or multi-select element. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return array an array of all selected option labels in the specified select drop-down + */ + public function getSelectedLabels($selectLocator) + { + return $this->getStringArray("getSelectedLabels", array($selectLocator)); + } + + + /** + * Gets option label (visible text) for selected option in the specified select element. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return string the selected option label in the specified select drop-down + */ + public function getSelectedLabel($selectLocator) + { + return $this->getString("getSelectedLabel", array($selectLocator)); + } + + + /** + * Gets all option values (value attributes) for selected options in the specified select or multi-select element. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return array an array of all selected option values in the specified select drop-down + */ + public function getSelectedValues($selectLocator) + { + return $this->getStringArray("getSelectedValues", array($selectLocator)); + } + + + /** + * Gets option value (value attribute) for selected option in the specified select element. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return string the selected option value in the specified select drop-down + */ + public function getSelectedValue($selectLocator) + { + return $this->getString("getSelectedValue", array($selectLocator)); + } + + + /** + * Gets all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return array an array of all selected option indexes in the specified select drop-down + */ + public function getSelectedIndexes($selectLocator) + { + return $this->getStringArray("getSelectedIndexes", array($selectLocator)); + } + + + /** + * Gets option index (option number, starting at 0) for selected option in the specified select element. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return string the selected option index in the specified select drop-down + */ + public function getSelectedIndex($selectLocator) + { + return $this->getString("getSelectedIndex", array($selectLocator)); + } + + + /** + * Gets all option element IDs for selected options in the specified select or multi-select element. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return array an array of all selected option IDs in the specified select drop-down + */ + public function getSelectedIds($selectLocator) + { + return $this->getStringArray("getSelectedIds", array($selectLocator)); + } + + + /** + * Gets option element ID for selected option in the specified select element. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return string the selected option ID in the specified select drop-down + */ + public function getSelectedId($selectLocator) + { + return $this->getString("getSelectedId", array($selectLocator)); + } + + + /** + * Determines whether some option in a drop-down menu is selected. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return boolean true if some option has been selected, false otherwise + */ + public function isSomethingSelected($selectLocator) + { + return $this->getBoolean("isSomethingSelected", array($selectLocator)); + } + + + /** + * Gets all option labels in the specified select drop-down. + * + * @access public + * @param string $selectLocator an element locator identifying a drop-down menu + * @return array an array of all option labels in the specified select drop-down + */ + public function getSelectOptions($selectLocator) + { + return $this->getStringArray("getSelectOptions", array($selectLocator)); + } + + + /** + * Gets the value of an element attribute. The value of the attribute may + * differ across browsers (this is the case for the "style" attribute, for + * example). + * + * @access public + * @param string $attributeLocator an element locator followed by an @ sign and then the name of the attribute, e.g. "foo@bar" + * @return string the value of the specified attribute + */ + public function getAttribute($attributeLocator) + { + return $this->getString("getAttribute", array($attributeLocator)); + } + + + /** + * Verifies that the specified text pattern appears somewhere on the rendered page shown to the user. + * + * @access public + * @param string $pattern a pattern to match with the text of the page + * @return boolean true if the pattern matches the text, false otherwise + */ + public function isTextPresent($pattern) + { + return $this->getBoolean("isTextPresent", array($pattern)); + } + + + /** + * Verifies that the specified element is somewhere on the page. + * + * @access public + * @param string $locator an element locator + * @return boolean true if the element is present, false otherwise + */ + public function isElementPresent($locator) + { + return $this->getBoolean("isElementPresent", array($locator)); + } + + + /** + * Determines if the specified element is visible. An + * element can be rendered invisible by setting the CSS "visibility" + * property to "hidden", or the "display" property to "none", either for the + * element itself or one if its ancestors. This method will fail if + * the element is not present. + * + * @access public + * @param string $locator an element locator + * @return boolean true if the specified element is visible, false otherwise + */ + public function isVisible($locator) + { + return $this->getBoolean("isVisible", array($locator)); + } + + + /** + * Determines whether the specified input element is editable, ie hasn't been disabled. + * This method will fail if the specified element isn't an input element. + * + * @access public + * @param string $locator an element locator + * @return boolean true if the input element is editable, false otherwise + */ + public function isEditable($locator) + { + return $this->getBoolean("isEditable", array($locator)); + } + + + /** + * Returns the IDs of all buttons on the page. + * + * <p> + * If a given button has no ID, it will appear as "" in this array. + * </p> + * + * @access public + * @return array the IDs of all buttons on the page + */ + public function getAllButtons() + { + return $this->getStringArray("getAllButtons", array()); + } + + + /** + * Returns the IDs of all links on the page. + * + * <p> + * If a given link has no ID, it will appear as "" in this array. + * </p> + * + * @access public + * @return array the IDs of all links on the page + */ + public function getAllLinks() + { + return $this->getStringArray("getAllLinks", array()); + } + + + /** + * Returns the IDs of all input fields on the page. + * + * <p> + * If a given field has no ID, it will appear as "" in this array. + * </p> + * + * @access public + * @return array the IDs of all field on the page + */ + public function getAllFields() + { + return $this->getStringArray("getAllFields", array()); + } + + + /** + * Returns an array of JavaScript property values from all known windows having one. + * + * @access public + * @param string $attributeName name of an attribute on the windows + * @return array the set of values of this attribute from all known windows. + */ + public function getAttributeFromAllWindows($attributeName) + { + return $this->getStringArray("getAttributeFromAllWindows", array($attributeName)); + } + + + /** + * deprecated - use dragAndDrop instead + * + * @access public + * @param string $locator an element locator + * @param string $movementsString offset in pixels from the current location to which the element should be moved, e.g., "+70,-300" + */ + public function dragdrop($locator, $movementsString) + { + $this->doCommand("dragdrop", array($locator, $movementsString)); + } + + + /** + * Configure the number of pixels between "mousemove" events during dragAndDrop commands (default=10). + * <p> + * Setting this value to 0 means that we'll send a "mousemove" event to every single pixel + * in between the start location and the end location; that can be very slow, and may + * cause some browsers to force the JavaScript to timeout. + * </p><p> + * If the mouse speed is greater than the distance between the two dragged objects, we'll + * just send one "mousemove" at the start location and then one final one at the end location. + * </p> + * + * @access public + * @param string $pixels the number of pixels between "mousemove" events + */ + public function setMouseSpeed($pixels) + { + $this->doCommand("setMouseSpeed", array($pixels)); + } + + + /** + * Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10). + * + * @access public + * @return number the number of pixels between "mousemove" events during dragAndDrop commands (default=10) + */ + public function getMouseSpeed() + { + return $this->getNumber("getMouseSpeed", array()); + } + + + /** + * Drags an element a certain distance and then drops it + * + * @access public + * @param string $locator an element locator + * @param string $movementsString offset in pixels from the current location to which the element should be moved, e.g., "+70,-300" + */ + public function dragAndDrop($locator, $movementsString) + { + $this->doCommand("dragAndDrop", array($locator, $movementsString)); + } + + + /** + * Drags an element and drops it on another element + * + * @access public + * @param string $locatorOfObjectToBeDragged an element to be dragged + * @param string $locatorOfDragDestinationObject an element whose location (i.e., whose center-most pixel) will be the point where locatorOfObjectToBeDragged is dropped + */ + public function dragAndDropToObject($locatorOfObjectToBeDragged, $locatorOfDragDestinationObject) + { + $this->doCommand("dragAndDropToObject", array($locatorOfObjectToBeDragged, $locatorOfDragDestinationObject)); + } + + + /** + * Gives focus to the currently selected window + * + * @access public + */ + public function windowFocus() + { + $this->doCommand("windowFocus", array()); + } + + + /** + * Resize currently selected window to take up the entire screen + * + * @access public + */ + public function windowMaximize() + { + $this->doCommand("windowMaximize", array()); + } + + + /** + * Returns the IDs of all windows that the browser knows about in an array. + * + * @access public + * @return array Array of identifiers of all windows that the browser knows about. + */ + public function getAllWindowIds() + { + return $this->getStringArray("getAllWindowIds", array()); + } + + + /** + * Returns the names of all windows that the browser knows about in an array. + * + * @access public + * @return array Array of names of all windows that the browser knows about. + */ + public function getAllWindowNames() + { + return $this->getStringArray("getAllWindowNames", array()); + } + + + /** + * Returns the titles of all windows that the browser knows about in an array. + * + * @access public + * @return array Array of titles of all windows that the browser knows about. + */ + public function getAllWindowTitles() + { + return $this->getStringArray("getAllWindowTitles", array()); + } + + + /** + * Returns the entire HTML source between the opening and + * closing "html" tags. + * + * @access public + * @return string the entire HTML source + */ + public function getHtmlSource() + { + return $this->getString("getHtmlSource", array()); + } + + + /** + * Moves the text cursor to the specified position in the given input element or textarea. + * This method will fail if the specified element isn't an input element or textarea. + * + * @access public + * @param string $locator an element locator pointing to an input element or textarea + * @param string $position the numerical position of the cursor in the field; position should be 0 to move the position to the beginning of the field. You can also set the cursor to -1 to move it to the end of the field. + */ + public function setCursorPosition($locator, $position) + { + $this->doCommand("setCursorPosition", array($locator, $position)); + } + + + /** + * Get the relative index of an element to its parent (starting from 0). The comment node and empty text node + * will be ignored. + * + * @access public + * @param string $locator an element locator pointing to an element + * @return number of relative index of the element to its parent (starting from 0) + */ + public function getElementIndex($locator) + { + return $this->getNumber("getElementIndex", array($locator)); + } + + + /** + * Check if these two elements have same parent and are ordered siblings in the DOM. Two same elements will + * not be considered ordered. + * + * @access public + * @param string $locator1 an element locator pointing to the first element + * @param string $locator2 an element locator pointing to the second element + * @return boolean true if element1 is the previous sibling of element2, false otherwise + */ + public function isOrdered($locator1, $locator2) + { + return $this->getBoolean("isOrdered", array($locator1, $locator2)); + } + + + /** + * Retrieves the horizontal position of an element + * + * @access public + * @param string $locator an element locator pointing to an element OR an element itself + * @return number of pixels from the edge of the frame. + */ + public function getElementPositionLeft($locator) + { + return $this->getNumber("getElementPositionLeft", array($locator)); + } + + + /** + * Retrieves the vertical position of an element + * + * @access public + * @param string $locator an element locator pointing to an element OR an element itself + * @return number of pixels from the edge of the frame. + */ + public function getElementPositionTop($locator) + { + return $this->getNumber("getElementPositionTop", array($locator)); + } + + + /** + * Retrieves the width of an element + * + * @access public + * @param string $locator an element locator pointing to an element + * @return number width of an element in pixels + */ + public function getElementWidth($locator) + { + return $this->getNumber("getElementWidth", array($locator)); + } + + + /** + * Retrieves the height of an element + * + * @access public + * @param string $locator an element locator pointing to an element + * @return number height of an element in pixels + */ + public function getElementHeight($locator) + { + return $this->getNumber("getElementHeight", array($locator)); + } + + + /** + * Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers. + * + * <p> + * Specifically, if the cursor/selection has been cleared by JavaScript, this command will tend to + * return the position of the last location of the cursor, even though the cursor is now gone from the page. This is filed as SEL-243. + * </p> + * This method will fail if the specified element isn't an input element or textarea, or there is no cursor in the element. + * + * @access public + * @param string $locator an element locator pointing to an input element or textarea + * @return number the numerical position of the cursor in the field + */ + public function getCursorPosition($locator) + { + return $this->getNumber("getCursorPosition", array($locator)); + } + + + /** + * Returns the specified expression. + * + * <p> + * This is useful because of JavaScript preprocessing. + * It is used to generate commands like assertExpression and waitForExpression. + * </p> + * + * @access public + * @param string $expression the value to return + * @return string the value passed in + */ + public function getExpression($expression) + { + return $this->getString("getExpression", array($expression)); + } + + + /** + * Returns the number of nodes that match the specified xpath, eg. "//table" would give + * the number of tables. + * + * @access public + * @param string $xpath the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you. + * @return number the number of nodes that match the specified xpath + */ + public function getXpathCount($xpath) + { + return $this->getNumber("getXpathCount", array($xpath)); + } + + + /** + * Temporarily sets the "id" attribute of the specified element, so you can locate it in the future + * using its ID rather than a slow/complicated XPath. This ID will disappear once the page is + * reloaded. + * + * @access public + * @param string $locator an element locator pointing to an element + * @param string $identifier a string to be used as the ID of the specified element + */ + public function assignId($locator, $identifier) + { + $this->doCommand("assignId", array($locator, $identifier)); + } + + + /** + * Specifies whether Selenium should use the native in-browser implementation + * of XPath (if any native version is available); if you pass "false" to + * this function, we will always use our pure-JavaScript xpath library. + * Using the pure-JS xpath library can improve the consistency of xpath + * element locators between different browser vendors, but the pure-JS + * version is much slower than the native implementations. + * + * @access public + * @param string $allow boolean, true means we'll prefer to use native XPath; false means we'll only use JS XPath + */ + public function allowNativeXpath($allow) + { + $this->doCommand("allowNativeXpath", array($allow)); + } + + + /** + * Specifies whether Selenium will ignore xpath attributes that have no + * value, i.e. are the empty string, when using the non-native xpath + * evaluation engine. You'd want to do this for performance reasons in IE. + * However, this could break certain xpaths, for example an xpath that looks + * for an attribute whose value is NOT the empty string. + * + * The hope is that such xpaths are relatively rare, but the user should + * have the option of using them. Note that this only influences xpath + * evaluation when using the ajaxslt engine (i.e. not "javascript-xpath"). + * + * @access public + * @param string $ignore boolean, true means we'll ignore attributes without value at the expense of xpath "correctness"; false means we'll sacrifice speed for correctness. + */ + public function ignoreAttributesWithoutValue($ignore) + { + $this->doCommand("ignoreAttributesWithoutValue", array($ignore)); + } + + + /** + * Runs the specified JavaScript snippet repeatedly until it evaluates to "true". + * The snippet may have multiple lines, but only the result of the last line + * will be considered. + * + * <p> + * Note that, by default, the snippet will be run in the runner's test window, not in the window + * of your application. To get the window of your application, you can use + * the JavaScript snippet <code>selenium.browserbot.getCurrentWindow()</code>, and then + * run your JavaScript in there + * </p> + * + * @access public + * @param string $script the JavaScript snippet to run + * @param string $timeout a timeout in milliseconds, after which this command will return with an error + */ + public function waitForCondition($script, $timeout) + { + $this->doCommand("waitForCondition", array($script, $timeout)); + } + + + /** + * Specifies the amount of time that Selenium will wait for actions to complete. + * + * <p> + * Actions that require waiting include "open" and the "waitFor*" actions. + * </p> + * The default timeout is 30 seconds. + * + * @access public + * @param string $timeout a timeout in milliseconds, after which the action will return with an error + */ + public function setTimeout($timeout) + { + $this->doCommand("setTimeout", array($timeout)); + } + + + /** + * Waits for a new page to load. + * + * <p> + * You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc. + * (which are only available in the JS API). + * </p><p> + * Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded" + * flag when it first notices a page load. Running any other Selenium command after + * turns the flag to false. Hence, if you want to wait for a page to load, you must + * wait immediately after a Selenium command that caused a page-load. + * </p> + * + * @access public + * @param string $timeout a timeout in milliseconds, after which this command will return with an error + */ + public function waitForPageToLoad($timeout) + { + $this->doCommand("waitForPageToLoad", array($timeout)); + } + + + /** + * Waits for a new frame to load. + * + * <p> + * Selenium constantly keeps track of new pages and frames loading, + * and sets a "newPageLoaded" flag when it first notices a page load. + * </p> + * + * See waitForPageToLoad for more information. + * + * @access public + * @param string $frameAddress FrameAddress from the server side + * @param string $timeout a timeout in milliseconds, after which this command will return with an error + */ + public function waitForFrameToLoad($frameAddress, $timeout) + { + $this->doCommand("waitForFrameToLoad", array($frameAddress, $timeout)); + } + + + /** + * Return all cookies of the current page under test. + * + * @access public + * @return string all cookies of the current page under test + */ + public function getCookie() + { + return $this->getString("getCookie", array()); + } + + + /** + * Returns the value of the cookie with the specified name, or throws an error if the cookie is not present. + * + * @access public + * @param string $name the name of the cookie + * @return string the value of the cookie + */ + public function getCookieByName($name) + { + return $this->getString("getCookieByName", array($name)); + } + + + /** + * Returns true if a cookie with the specified name is present, or false otherwise. + * + * @access public + * @param string $name the name of the cookie + * @return boolean true if a cookie with the specified name is present, or false otherwise. + */ + public function isCookiePresent($name) + { + return $this->getBoolean("isCookiePresent", array($name)); + } + + + /** + * Create a new cookie whose path and domain are same with those of current page + * under test, unless you specified a path for this cookie explicitly. + * + * @access public + * @param string $nameValuePair name and value of the cookie in a format "name=value" + * @param string $optionsString options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a subset of the current domain will usually fail. + */ + public function createCookie($nameValuePair, $optionsString) + { + $this->doCommand("createCookie", array($nameValuePair, $optionsString)); + } + + + /** + * Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you + * need to delete it using the exact same path and domain that were used to create the cookie. + * If the path is wrong, or the domain is wrong, the cookie simply won't be deleted. Also + * note that specifying a domain that isn't a subset of the current domain will usually fail. + * + * Since there's no way to discover at runtime the original path and domain of a given cookie, + * we've added an option called 'recurse' to try all sub-domains of the current domain with + * all paths that are a subset of the current path. Beware; this option can be slow. In + * big-O notation, it operates in O(n*m) time, where n is the number of dots in the domain + * name and m is the number of slashes in the path. + * + * @access public + * @param string $name the name of the cookie to be deleted + * @param string $optionsString options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail. + */ + public function deleteCookie($name, $optionsString) + { + $this->doCommand("deleteCookie", array($name, $optionsString)); + } + + + /** + * Calls deleteCookie with recurse=true on all cookies visible to the current page. + * As noted on the documentation for deleteCookie, recurse=true can be much slower + * than simply deleting the cookies using a known domain/path. + * + * @access public + */ + public function deleteAllVisibleCookies() + { + $this->doCommand("deleteAllVisibleCookies", array()); + } + + + /** + * Sets the threshold for browser-side logging messages; log messages beneath this threshold will be discarded. + * Valid logLevel strings are: "debug", "info", "warn", "error" or "off". + * To see the browser logs, you need to + * either show the log window in GUI mode, or enable browser-side logging in Selenium RC. + * + * @access public + * @param string $logLevel one of the following: "debug", "info", "warn", "error" or "off" + */ + public function setBrowserLogLevel($logLevel) + { + $this->doCommand("setBrowserLogLevel", array($logLevel)); + } + + + /** + * Creates a new "script" tag in the body of the current test window, and + * adds the specified text into the body of the command. Scripts run in + * this way can often be debugged more easily than scripts executed using + * Selenium's "getEval" command. Beware that JS exceptions thrown in these script + * tags aren't managed by Selenium, so you should probably wrap your script + * in try/catch blocks if there is any chance that the script will throw + * an exception. + * + * @access public + * @param string $script the JavaScript snippet to run + */ + public function runScript($script) + { + $this->doCommand("runScript", array($script)); + } + + + /** + * Defines a new function for Selenium to locate elements on the page. + * For example, + * if you define the strategy "foo", and someone runs click("foo=blah"), we'll + * run your function, passing you the string "blah", and click on the element + * that your function + * returns, or throw an "Element not found" error if your function returns null. + * + * We'll pass three arguments to your function: + * + * <ul> + * + * <li> + * locator: the string the user passed in + * </li> + * <li> + * inWindow: the currently selected window + * </li> + * <li> + * inDocument: the currently selected document + * </li> + * </ul> + * The function must return null if the element can't be found. + * + * @access public + * @param string $strategyName the name of the strategy to define; this should use only letters [a-zA-Z] with no spaces or other punctuation. + * @param string $functionDefinition a string defining the body of a function in JavaScript. For example: <code>return inDocument.getElementById(locator);</code> + */ + public function addLocationStrategy($strategyName, $functionDefinition) + { + $this->doCommand("addLocationStrategy", array($strategyName, $functionDefinition)); + } + + + /** + * Saves the entire contents of the current window canvas to a PNG file. + * Contrast this with the captureScreenshot command, which captures the + * contents of the OS viewport (i.e. whatever is currently being displayed + * on the monitor), and is implemented in the RC only. Currently this only + * works in Firefox when running in chrome mode, and in IE non-HTA using + * the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly + * borrowed from the Screengrab! Firefox extension. Please see + * http://www.screengrab.org and http://snapsie.sourceforge.net/ for + * details. + * + * @access public + * @param string $filename the path to the file to persist the screenshot as. No filename extension will be appended by default. Directories will not be created if they do not exist, and an exception will be thrown, possibly by native code. + * @param string $kwargs a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" . Currently valid options: <dl> +<dt>background</dt> +<dd>the background CSS for the HTML document. This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text).</dd> +</dl> + */ + public function captureEntirePageScreenshot($filename, $kwargs) + { + $this->doCommand("captureEntirePageScreenshot", array($filename, $kwargs)); + } + + + /** + * Executes a command rollup, which is a series of commands with a unique + * name, and optionally arguments that control the generation of the set of + * commands. If any one of the rolled-up commands fails, the rollup is + * considered to have failed. Rollups may also contain nested rollups. + * + * @access public + * @param string $rollupName the name of the rollup command + * @param string $kwargs keyword arguments string that influences how the rollup expands into commands + */ + public function rollup($rollupName, $kwargs) + { + $this->doCommand("rollup", array($rollupName, $kwargs)); + } + + + /** + * Loads script content into a new script tag in the Selenium document. This + * differs from the runScript command in that runScript adds the script tag + * to the document of the AUT, not the Selenium document. The following + * entities in the script content are replaced by the characters they + * represent: + * + * &lt; + * &gt; + * &amp; + * + * The corresponding remove command is removeScript. + * + * @access public + * @param string $scriptContent the Javascript content of the script to add + * @param string $scriptTagId (optional) the id of the new script tag. If specified, and an element with this id already exists, this operation will fail. + */ + public function addScript($scriptContent, $scriptTagId) + { + $this->doCommand("addScript", array($scriptContent, $scriptTagId)); + } + + + /** + * Removes a script tag from the Selenium document identified by the given + * id. Does nothing if the referenced tag doesn't exist. + * + * @access public + * @param string $scriptTagId the id of the script element to remove. + */ + public function removeScript($scriptTagId) + { + $this->doCommand("removeScript", array($scriptTagId)); + } + + + /** + * Allows choice of one of the available libraries. + * + * @access public + * @param string $libraryName name of the desired library Only the following three can be chosen: <ul> +<li>"ajaxslt" - Google's library</li> +<li>"javascript-xpath" - Cybozu Labs' faster library</li> +<li>"default" - The default library. Currently the default library is "ajaxslt" .</li> +</ul> If libraryName isn't one of these three, then no change will be made. + */ + public function useXpathLibrary($libraryName) + { + $this->doCommand("useXpathLibrary", array($libraryName)); + } + + + /** + * Writes a message to the status bar and adds a note to the browser-side + * log. + * + * @access public + * @param string $context the message to be sent to the browser + */ + public function setContext($context) + { + $this->doCommand("setContext", array($context)); + } + + + /** + * Sets a file input (upload) field to the file listed in fileLocator + * + * @access public + * @param string $fieldLocator an element locator + * @param string $fileLocator a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator), Selenium RC may need to transfer the file to the local machine before attaching the file in a web page form. This is common in selenium grid configurations where the RC server driving the browser is not the same machine that started the test. Supported Browsers: Firefox ("*chrome") only. + */ + public function attachFile($fieldLocator, $fileLocator) + { + $this->doCommand("attachFile", array($fieldLocator, $fileLocator)); + } + + + /** + * Captures a PNG screenshot to the specified file. + * + * @access public + * @param string $filename the absolute path to the file to be written, e.g. "c:\blah\screenshot.png" + */ + public function captureScreenshot($filename) + { + $this->doCommand("captureScreenshot", array($filename)); + } + + + /** + * Capture a PNG screenshot. It then returns the file as a base 64 encoded string. + * + * @access public + * @return string The base 64 encoded string of the screen shot (PNG file) + */ + public function captureScreenshotToString() + { + return $this->getString("captureScreenshotToString", array()); + } + + + /** + * Downloads a screenshot of the browser current window canvas to a + * based 64 encoded PNG file. The <i>entire</i> windows canvas is captured, + * including parts rendered outside of the current view port. + * + * Currently this only works in Mozilla and when running in chrome mode. + * + * @access public + * @param string $kwargs A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text). + * @return string The base 64 encoded string of the page screenshot (PNG file) + */ + public function captureEntirePageScreenshotToString($kwargs) + { + return $this->getString("captureEntirePageScreenshotToString", array($kwargs)); + } + + + /** + * Kills the running Selenium Server and all browser sessions. After you run this command, you will no longer be able to send + * commands to the server; you can't remotely start the server once it has been stopped. Normally + * you should prefer to run the "stop" command, which terminates the current browser session, rather than + * shutting down the entire server. + * + * @access public + */ + public function shutDownSeleniumServer() + { + $this->doCommand("shutDownSeleniumServer", array()); + } + + + /** + * Retrieve the last messages logged on a specific remote control. Useful for error reports, especially + * when running multiple remote controls in a distributed environment. The maximum number of log messages + * that can be retrieve is configured on remote control startup. + * + * @access public + * @return string The last N log messages as a multi-line string. + */ + public function retrieveLastRemoteControlLogs() + { + return $this->getString("retrieveLastRemoteControlLogs", array()); + } + + + /** + * Simulates a user pressing a key (without releasing it yet) by sending a native operating system keystroke. + * This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing + * a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and + * metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular + * element, focus on the element first before running this command. + * + * @access public + * @param string $keycode an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! + */ + public function keyDownNative($keycode) + { + $this->doCommand("keyDownNative", array($keycode)); + } + + + /** + * Simulates a user releasing a key by sending a native operating system keystroke. + * This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing + * a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and + * metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular + * element, focus on the element first before running this command. + * + * @access public + * @param string $keycode an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! + */ + public function keyUpNative($keycode) + { + $this->doCommand("keyUpNative", array($keycode)); + } + + + /** + * Simulates a user pressing and releasing a key by sending a native operating system keystroke. + * This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing + * a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and + * metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular + * element, focus on the element first before running this command. + * + * @access public + * @param string $keycode an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! + */ + public function keyPressNative($keycode) + { + $this->doCommand("keyPressNative", array($keycode)); + } + + + protected function doCommand($verb, $args = array()) + { + $url = sprintf('http://%s:%s/selenium-server/driver/?cmd=%s', $this->host, $this->port, urlencode($verb)); + for ($i = 0; $i < count($args); $i++) { + $argNum = strval($i + 1); + $url .= sprintf('&%s=%s', $argNum, urlencode(trim($args[$i]))); + } + + if (isset($this->sessionId)) { + $url .= sprintf('&%s=%s', 'sessionId', $this->sessionId); + } + + if (!$handle = fopen($url, 'r')) { + throw new Testing_Selenium_Exception('Cannot connected to Selenium RC Server'); + } + + stream_set_blocking($handle, false); + $response = stream_get_contents($handle); + fclose($handle); + + return $response; + } + + private function getNumber($verb, $args = array()) + { + $result = $this->getString($verb, $args); + + if (!is_numeric($result)) { + throw new Testing_Selenium_Exception('result is not numeric.'); + } + return $result; + } + + protected function getString($verb, $args = array()) + { + $result = $this->doCommand($verb, $args); + return (strlen($result) > 3) ? substr($result, 3) : ''; + } + + private function getStringArray($verb, $args = array()) + { + $csv = $this->getString($verb, $args); + $token = ''; + $tokens = array(); + $letters = preg_split('//', $csv, -1, PREG_SPLIT_NO_EMPTY); + for ($i = 0; $i < count($letters); $i++) { + $letter = $letters[$i]; + switch($letter) { + case '\\': + $i++; + $letter = $letters[$i]; + $token = $token . $letter; + break; + case ',': + array_push($tokens, $token); + $token = ''; + break; + default: + $token = $token . $letter; + break; + } + } + array_push($tokens, $token); + return $tokens; + } + + private function getBoolean($verb, $args = array()) + { + $result = $this->getString($verb, $args); + switch ($result) { + case 'true': + return true; + case 'false': + return false; + default: + throw new Testing_Selenium_Exception('result is neither "true" or "false": ' . $result); + } + } +} +?> \ No newline at end of file diff --git a/Testing/Selenium/Exception.php b/Testing/Selenium/Exception.php new file mode 100644 index 0000000..9069ae5 --- /dev/null +++ b/Testing/Selenium/Exception.php @@ -0,0 +1,40 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ + +/** + * Exception Class for Selenium + * + * PHP versions 5 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/** + * uses PEAR_Exception + */ +require_once 'PEAR/Exception.php'; + +/** + * Testing_Selenium_Exception + * + * @category Testing + * @package Testing_Selenium + * @author Shin Ohno <ganchiku at gmail dot com> + * @author Bjoern Schotte <schotte at mayflower dot de> + * @version @package_version@ + */ +class Testing_Selenium_Exception extends PEAR_Exception +{ +} +?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php index 45a5057..d44ccc3 100644 --- a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -1,192 +1,193 @@ <?php require_once 'src/selenium_helper/SeleniumDrivenUser.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; require_once 'configuration/Configuration.php'; class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase { private static $selenium_execution_context; private static $selenium_driven_user; + private static $selenium_test_page_path; public static function setUpBeforeClass() - { - $configuration = new Configuration(); - self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); + { + $configuration = new Configuration(); + self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); - self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file://".self::$selenium_test_page_path); - self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); + self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file://".self::$selenium_test_page_path); + self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); } public static function tearDownAfterClass() { - self::$selenium_driven_user->destroy(); + self::$selenium_driven_user->destroy(); } public function setUp() { self::$selenium_driven_user->goesTo("file://".self::$selenium_test_page_path); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } /** * @test */ public function shouldNotSeeShouldSucceedWhenElementIsNotFound() { self::$selenium_driven_user->shouldNotSee("//*[id('id_that_dont_exist')]"); } /** * @test */ public function shouldNotSeeShouldFailWhenElementIsFound() { try { self::$selenium_driven_user->shouldNotSee("//*[id('test_span')]"); self::fail("shouldNotSee should have failed"); } catch (Exception $e) { } } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_radio']"); self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_driven_user->selects("Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_driven_user->selects("Option 2")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } } ?> \ No newline at end of file
xto/SUTA
52dd6e7ea63d81b16fa4021c1bfa61459c074be2
Adding configuration.
diff --git a/configuration/Configuration.php b/configuration/Configuration.php new file mode 100644 index 0000000..254640e --- /dev/null +++ b/configuration/Configuration.php @@ -0,0 +1,11 @@ +<?php + class Configuration { + private $SUTA_path = "/home/frank/projects/SUTA/"; + private $selenium_test_page_path = "expectations/selenium_expectations/selenium_test_page.html"; + + public function getSeleniumTestPagePath() + { + return $this->SUTA_path.$this->selenium_test_page_path; + } + } +?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php b/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php index 638c413..a33886b 100644 --- a/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php +++ b/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php @@ -1,162 +1,166 @@ <?php require_once 'src/selenium_helper/SeleniumTestSubject.php'; + require_once 'configuration/Configuration.php'; class SeleniumTestSubjectExpectations extends PHPUnit_Framework_TestCase { private static $selenium_test_subject; + private static $selenium_test_page_path; public static function setUpBeforeClass() { - self::$selenium_test_subject = new SeleniumTestSubject("firefox","file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + $configuration = new Configuration(); + self::$selenium_test_page_path = $configuration->getSeleniumTestPagePath(); + self::$selenium_test_subject = new SeleniumTestSubject("firefox","file://".self::$selenium_test_page_path); } public static function tearDownAfterClass() { self::$selenium_test_subject->destroy(); } public function setUp() { - self::$selenium_test_subject->goesTo("file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + self::$selenium_test_subject->goesTo("file://".self::$selenium_test_page_path); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_test_subject->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_test_subject->shouldSee("//*[id('test_span')]"); } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_test_subject->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_test_subject->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_test_subject->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_test_subject->clicks("//input[@name='test_checkbox']"); self::$selenium_test_subject->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_test_subject->clicks("//input[@name='test_radio']"); self::$selenium_test_subject->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_test_subject->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_test_subject->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_test_subject->selects("Unknown Option")->from("test_select"); self::$selenium_test_subject->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_test_subject->selects("Option")->from("test_select"); self::$selenium_test_subject->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_test_subject->selects("Option 2")->from("test_select"); self::$selenium_test_subject->shouldSee("//select/option[2]")->selected(); } } ?> \ No newline at end of file
xto/SUTA
9b80a36a03af8cddcb2228851345410263d19968
Added should raise expectation.
diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php index f5d9891..a45f70e 100644 --- a/expectations/ExpectationsExpectations.php +++ b/expectations/ExpectationsExpectations.php @@ -1,222 +1,253 @@ <?php require_once 'src/Expectations.php'; - + class ExpectationsExpectations extends PHPUnit_Framework_TestCase { /** * @test */ public function ShouldBeTrueShouldBehaveJustLikeassertTrue() { Expectations::shouldBeTrue(true); self::assertTrue(true); try { self::assertTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeFalseShouldBehaveJustLikeassertFalse() { Expectations::shouldBeFalse(false); self::assertFalse(false); try { self::assertFalse(True); throw new Exception("assertFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeFalse(true); throw new Exception("shouldBeFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldEqualShouldBehaveLikeAssertEqual() { self::assertEquals("tom","tom"); Expectations::shouldEqual("tom","tom"); try { self::assertEquals("foo", "bar"); throw new Exception("assertEquals should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldEqual("foo", "bar"); throw new Exception("shouldEqual should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotBeEqualShouldBehaveLikeAssertNotEquals() { self::assertNotEquals(1,2); Expectations::shouldNotEqual(1,2); try { self::assertNotEquals(1,1); throw new Exception("assertNotEquals should fail when both elements are equal"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotEqual(1,1); throw new Expection("shouldNotEqual should fail when both elements are equal"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeNullShouldBehaveLikeAssertNull() { Expectations::shouldBeNull(null); self::assertNull(null); try { self::assertNull("Something that isn't null"); throw new Exception("assertNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeNull("Something that isn't null"); throw new Exception("shouldBeNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotBeNullShouldBehaveLikeAssertNotNull() { self::assertNotNull("Something not null"); Expectations::shouldNotBeNull("Something not null"); try { self::assertNotNull(null); throw new Exception("assertNotNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotBeNull(null); throw new Exception("shoulNotdBeNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldContainShouldBehaveLikeAssertContains() { self::assertContains("tom","tom petty"); Expectations::shouldContain("tom", "tom petty"); try { self::assertContains("tom", "petty"); throw new Exception("assertContains should fail if the pattern is not in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldContain("tom", "petty"); throw new Exception("shoulContain should fail if the pattern is not in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotContainShouldBehaveLikeAssertNotContains() { self::assertNotContains("tom", "something else"); Expectations::shouldNotContain("tom", "something else"); try { self::assertNotContains("tom", "tom"); throw new Exception("assertNotContains should fail if the pattern is in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotContain("tom", "tom"); throw new Exception("shoulNotContain should fail if the pattern is in the value"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } + + /** + * @test + */ + public function ShouldRaiseExceptionShouldPassWhenExceptationRaisedMatchsExpectedException() + { + $expected = new Exception("patate"); + $actual = $expected; + Expectations::shouldRaiseException($actual, $expected); + } + + + /** + * @test + */ + public function ShouldRaiseExceptionShouldFailWhenExceptationRaisedDoesNotMatchExpectedException() + { + $expected = new Exception("potato"); + $actual = new ErrorException("potato"); + try + { + Expectations::shouldRaiseException($actual, $expected); + throw new Exception("shouldRaiseException() Should Fail When Exceptation Raised Does Not Match Expected Exception"); + }catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + } + + + } ?> \ No newline at end of file diff --git a/src/Expectations.php b/src/Expectations.php index 3db0c82..96d95be 100644 --- a/src/Expectations.php +++ b/src/Expectations.php @@ -1,67 +1,72 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; class Expectations extends PHPUnit_Framework_Assert { public static function shouldBeTrue($value, $message="") { self::assertThat($value, self::isTrue(), $message); } public static function shouldBeFalse($value, $message="") { self::assertThat($value, self::isFalse(), $message); } public static function shouldEqual($actual, $expected, $message = '') { self::assertEquals($expected, $actual, $message); } public static function shouldNotEqual($actual, $expected, $message = '') { self::assertNotEquals($expected, $actual, $message); } public static function shouldBeNull($value, $message = '') { self::assertNull($value, $message); } public static function shouldNotBeNull($value, $message = '') { self::assertNotNull($value, $message); } public static function shouldContain($pattern, $value, $message = '') { self::assertContains($pattern, $value, $message); } public static function shouldNotContain($pattern, $value, $message = '') { self::assertNotContains($pattern, $value, $message); } + + public static function shouldRaiseException($actual, $expected, $message="") + { + self::assertEquals(get_class($actual),get_class($expected), $message); + } } ?>
xto/SUTA
a512ba5d0bec64b2009a96761494fe9fe269c00a
Fixed a copy paste error in the message on shouldNotSeeFailure.. my bad... won't do it again
diff --git a/src/selenium_helper/SeleniumExpectations.php b/src/selenium_helper/SeleniumExpectations.php index 2ca7e34..53cde06 100644 --- a/src/selenium_helper/SeleniumExpectations.php +++ b/src/selenium_helper/SeleniumExpectations.php @@ -1,69 +1,69 @@ <?php class SeleniumExpectations { private $__seleniumExecutionContext; public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext= $seleniumExecutionContext; } private function __getLastVisitedLocation() { return $this->__seleniumExecutionContext->getLastVisitedLocation(); } private function __getSelenium() { return $this->__seleniumExecutionContext->getSelenium(); } private function __resetLastVisitedLocation() { $this->__seleniumExecutionContext->resetLastVisitedLocation(); } private function __setLastVisitedLocation($location) { $this->__seleniumExecutionContext->setLastVisitedLocation($location); } public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ Expectations::shouldBeTrue($this->__getSelenium()->isElementPresent($element_locator),$message ); $this->__setLastVisitedLocation($element_locator); } - public function shouldNotSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ + public function shouldNotSee($element_locator, $message = "Element was found! Verify that the locator is correct and that it should not be found !!!" ){ Expectations::shouldBeFalse($this->__getSelenium()->isElementPresent($element_locator),$message ); $this->__setLastVisitedLocation($element_locator); } public function withText($expected_text) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldContain($expected_text,$this->__getSelenium()->getText($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } public function checked() { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldBeTrue($this->__getSelenium()->isChecked($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } public function selected() { Expectations::shouldEqual($this->__getSelenium()->getValue($this->__getLastVisitedLocation()), $this->__getSelenium()->getSelectedLabel($this->__getLastVisitedLocation()."/..")); $this->__resetLastVisitedLocation(); } public function shouldBeOnPage($expected_url) { Expectations::shouldEqual($this->__getSelenium()->getLocation(), $expected_url); } } -?> \ No newline at end of file +?>
xto/SUTA
2e3534f463801f44f93936c3c0661922918fbfff
changed package version
diff --git a/.externalToolBuilders/PHPUNIT-AUTOTEST.launch b/.externalToolBuilders/PHPUNIT-AUTOTEST.launch index efffb4d..d9d5744 100644 --- a/.externalToolBuilders/PHPUNIT-AUTOTEST.launch +++ b/.externalToolBuilders/PHPUNIT-AUTOTEST.launch @@ -1,9 +1,10 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType"> <booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/> +<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="true"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="/usr/bin/php"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="/usr/bin/phpunit --include-path &quot;${project_loc}&quot; ${project_loc}/expectations/ExpectationsSuite.php"/> <booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc}"/> </launchConfiguration> diff --git a/package.xml b/package.xml index ca8fa12..e32452a 100644 --- a/package.xml +++ b/package.xml @@ -1,60 +1,60 @@ <?xml version="1.0" encoding="UTF-8"?> -<package packagerversion="0.1.1" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> +<package packagerversion="0.1.2" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> <name>SUTA</name> <channel>pear.php.net</channel> <summary>DSL for PHPUnit and Selenium</summary> <description>Simplfied Unit Test Addon for PHPUnit that allow a natural language syntax</description> <lead> <name>Xavier Tô</name> <user>xto</user> <email>[email protected]</email> <active>yes</active> </lead> <lead> <name>nicholas Lemay</name> <user>nichoalslemay</user> <email>[email protected]</email> <active>yes</active> </lead> <lead> <name>Francis Falardeau</name> <user>ffalardeau</user> <email>[email protected]</email> <active>yes</active> </lead> - <date>2010-02-16</date> - <time>23:00:00</time> + <date>2010-02-19</date> + <time>17:00:00</time> <version> - <release>0.1.1</release> - <api>0.1.1</api> + <release>0.1.2</release> + <api>0.1.2</api> </version> <stability> <release>beta</release> <api>beta</api> </stability> <license>GPL</license> <notes> http://github.com/xto/SUTA </notes> <contents> <dir name="/"> <file name="/SUTA/src/Expectations.php" role="php" /> <file name="/SUTA/src/TestSubject.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumDrivenUser.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumActions.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumExecutionContext.php" role="php" /> <file name="/SUTA/src/selenium_helper/SeleniumExpectations.php" role="php" /> </dir> </contents> <dependencies> <required> <php> <min>5.2.9</min> </php> <pearinstaller> <min>1.9.0</min> </pearinstaller> </required> </dependencies> <phprelease /> </package>
xto/SUTA
9a1e574373174f94f863a1f8c3b606f1a960c6b3
Added some expectations and of course their tests
diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php index 534e1ba..f5d9891 100644 --- a/expectations/ExpectationsExpectations.php +++ b/expectations/ExpectationsExpectations.php @@ -1,155 +1,222 @@ <?php require_once 'src/Expectations.php'; - + class ExpectationsExpectations extends PHPUnit_Framework_TestCase { - + /** * @test */ public function ShouldBeTrueShouldBehaveJustLikeassertTrue() { Expectations::shouldBeTrue(true); self::assertTrue(true); - - try + + try { self::assertTrue(false); throw new Exception("assertTrue should fail with false"); - } + } catch (PHPUnit_Framework_ExpectationFailedException $e) - { + { } - - try + + try { Expectations::shouldBeTrue(false); throw new Exception("assertTrue should fail with false"); - } + } catch (PHPUnit_Framework_ExpectationFailedException $e) - { + { } - - + + } - + /** * @test */ public function ShouldBeFalseShouldBehaveJustLikeassertFalse() { Expectations::shouldBeFalse(false); self::assertFalse(false); - - try + + try { self::assertFalse(True); throw new Exception("assertFalse should fail with true"); - } - catch (PHPUnit_Framework_ExpectationFailedException $e) - { } - - try + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try { Expectations::shouldBeFalse(true); throw new Exception("shouldBeFalse should fail with true"); - } - catch (PHPUnit_Framework_ExpectationFailedException $e) - { } - + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + } - - + + /** * @test */ public function ShouldEqualShouldBehaveLikeAssertEqual() { self::assertEquals("tom","tom"); Expectations::shouldEqual("tom","tom"); - - try + + try { self::assertEquals("foo", "bar"); throw new Exception("assertEquals should fail with foo and bar"); - } - catch (PHPUnit_Framework_ExpectationFailedException $e) - { } - - try + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try { Expectations::shouldEqual("foo", "bar"); throw new Exception("shouldEqual should fail with foo and bar"); - } - catch (PHPUnit_Framework_ExpectationFailedException $e) - { } - + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + } + + /** + * @test + */ + public function ShouldNotBeEqualShouldBehaveLikeAssertNotEquals() + { + self::assertNotEquals(1,2); + Expectations::shouldNotEqual(1,2); + + try + { + self::assertNotEquals(1,1); + throw new Exception("assertNotEquals should fail when both elements are equal"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try + { + Expectations::shouldNotEqual(1,1); + throw new Expection("shouldNotEqual should fail when both elements are equal"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } } - + /** * @test */ public function ShouldBeNullShouldBehaveLikeAssertNull() { Expectations::shouldBeNull(null); self::assertNull(null); - + try { self::assertNull("Something that isn't null"); - throw new Exception("assertNull should fail if something not null"); + throw new Exception("assertNull should fail if something not null"); } - catch (PHPUnit_Framework_ExpectationFailedException $e) + catch (PHPUnit_Framework_ExpectationFailedException $e) { } - + try { Expectations::shouldBeNull("Something that isn't null"); - throw new Exception("shouldBeNull should fail if something not null"); + throw new Exception("shouldBeNull should fail if something not null"); } - catch (PHPUnit_Framework_ExpectationFailedException $e) + catch (PHPUnit_Framework_ExpectationFailedException $e) { } } - + /** * @test - */ + */ public function ShouldNotBeNullShouldBehaveLikeAssertNotNull() { self::assertNotNull("Something not null"); Expectations::shouldNotBeNull("Something not null"); - + try { self::assertNotNull(null); throw new Exception("assertNotNull should fail if something null"); } - catch (PHPUnit_Framework_ExpectationFailedException $e) + catch (PHPUnit_Framework_ExpectationFailedException $e) { } - + try { Expectations::shouldNotBeNull(null); throw new Exception("shoulNotdBeNull should fail if something null"); } - catch (PHPUnit_Framework_ExpectationFailedException $e) + catch (PHPUnit_Framework_ExpectationFailedException $e) { } } - + /** * @test */ public function ShouldContainShouldBehaveLikeAssertContains() { self::assertContains("tom","tom petty"); Expectations::shouldContain("tom", "tom petty"); + + try { + self::assertContains("tom", "petty"); + throw new Exception("assertContains should fail if the pattern is not in the value"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try { + Expectations::shouldContain("tom", "petty"); + throw new Exception("shoulContain should fail if the pattern is not in the value"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + } + + /** + * @test + */ + public function ShouldNotContainShouldBehaveLikeAssertNotContains() + { + self::assertNotContains("tom", "something else"); + Expectations::shouldNotContain("tom", "something else"); + + try { + self::assertNotContains("tom", "tom"); + throw new Exception("assertNotContains should fail if the pattern is in the value"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try { + Expectations::shouldNotContain("tom", "tom"); + throw new Exception("shoulNotContain should fail if the pattern is in the value"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } } } ?> \ No newline at end of file diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php index 4ca3c80..4208832 100644 --- a/expectations/ExpectationsSuite.php +++ b/expectations/ExpectationsSuite.php @@ -1,41 +1,41 @@ - + <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ - + require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; require_once 'expectations/ExpectationsExpectations.php'; require_once 'expectations/TestSubjectExpectations.php'; require_once 'selenium_expectations/SeleniumDrivenUserExpectations.php'; - + class ExpectationsSuite { public static function suite() { $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); - + $suite->addTestSuite('ExpectationsExpectations'); $suite->addTestSuite('TestSubjectExpectations'); $suite->addTestSuite('SeleniumDrivenUserExpectations'); return $suite; } } - + ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php index ebdd3a2..4228c29 100644 --- a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -1,164 +1,187 @@ <?php require_once 'src/selenium_helper/SeleniumDrivenUser.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase { private static $selenium_execution_context; private static $selenium_driven_user; - + public static function setUpBeforeClass() { - self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file:///home/smpdev/SUTA/expectations/selenium_expectations/selenium_test_page.html"); self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); } - + public static function tearDownAfterClass() { self::$selenium_driven_user->destroy(); } - + public function setUp() { - self::$selenium_driven_user->goesTo("file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + self::$selenium_driven_user->goesTo("file:///home/smpdev/SUTA/expectations/selenium_expectations/selenium_test_page.html"); } - + /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } - + /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } - + + /** + * @test + */ + public function shouldNotSeeShouldSucceedWhenElementIsNotFound() + { + self::$selenium_driven_user->shouldNotSee("//*[id('id_that_dont_exist')]"); + } + + /** + * @test + */ + public function shouldNotSeeShouldFailWhenElementIsFound() + { + try + { + self::$selenium_driven_user->shouldNotSee("//*[id('test_span')]"); + self::fail("shouldNotSee should have failed"); + } + catch (Exception $e) + { + } + } + /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } - + /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } - + /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } - + /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); - + } - + /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_radio']"); self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); - + } - + /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } - + /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } - + /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } - + /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_driven_user->selects("Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } - + /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_driven_user->selects("Option 2")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } } ?> \ No newline at end of file diff --git a/src/Expectations.php b/src/Expectations.php index d0db76e..3db0c82 100644 --- a/src/Expectations.php +++ b/src/Expectations.php @@ -1,57 +1,67 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau - + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. - + */ require_once 'PHPUnit/Framework.php'; - - class Expectations extends PHPUnit_Framework_Assert + + class Expectations extends PHPUnit_Framework_Assert { - public static function shouldBeTrue($value, $message="") - { - self::assertThat($value, self::isTrue(), $message); - } - - public static function shouldBeFalse($value, $message="") - { - self::assertThat($value, self::isFalse(), $message); - } - - public static function shouldEqual($actual, $expected, $message = '') - { - self::assertEquals($expected, $actual, $message); - } - - public static function shouldBeNull($value, $message = '') - { - self::assertNull($value, $message); - } - - public static function shouldNotBeNull($value, $message = '') - { - self::assertNotNull($value, $message); - } - - public static function shouldContain($pattern, $value, $message = '') - { - self::assertContains($pattern, $value, $message); - } + public static function shouldBeTrue($value, $message="") + { + self::assertThat($value, self::isTrue(), $message); + } + + public static function shouldBeFalse($value, $message="") + { + self::assertThat($value, self::isFalse(), $message); + } + + public static function shouldEqual($actual, $expected, $message = '') + { + self::assertEquals($expected, $actual, $message); + } + + public static function shouldNotEqual($actual, $expected, $message = '') + { + self::assertNotEquals($expected, $actual, $message); + } + public static function shouldBeNull($value, $message = '') + { + self::assertNull($value, $message); + } + + public static function shouldNotBeNull($value, $message = '') + { + self::assertNotNull($value, $message); + } + + public static function shouldContain($pattern, $value, $message = '') + { + self::assertContains($pattern, $value, $message); + } + + public static function shouldNotContain($pattern, $value, $message = '') + { + self::assertNotContains($pattern, $value, $message); + } + } ?> diff --git a/src/selenium_helper/SeleniumExpectations.php b/src/selenium_helper/SeleniumExpectations.php index 9ed5d3d..2ca7e34 100644 --- a/src/selenium_helper/SeleniumExpectations.php +++ b/src/selenium_helper/SeleniumExpectations.php @@ -1,64 +1,69 @@ <?php class SeleniumExpectations { - + private $__seleniumExecutionContext; - + public function __construct($seleniumExecutionContext) { - $this->__seleniumExecutionContext= $seleniumExecutionContext; + $this->__seleniumExecutionContext= $seleniumExecutionContext; } - + private function __getLastVisitedLocation() { return $this->__seleniumExecutionContext->getLastVisitedLocation(); } - + private function __getSelenium() { return $this->__seleniumExecutionContext->getSelenium(); } private function __resetLastVisitedLocation() { $this->__seleniumExecutionContext->resetLastVisitedLocation(); } - + private function __setLastVisitedLocation($location) { $this->__seleniumExecutionContext->setLastVisitedLocation($location); } - + public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ Expectations::shouldBeTrue($this->__getSelenium()->isElementPresent($element_locator),$message ); $this->__setLastVisitedLocation($element_locator); } - + + public function shouldNotSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ + Expectations::shouldBeFalse($this->__getSelenium()->isElementPresent($element_locator),$message ); + $this->__setLastVisitedLocation($element_locator); + } + public function withText($expected_text) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldContain($expected_text,$this->__getSelenium()->getText($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } - + public function checked() { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldBeTrue($this->__getSelenium()->isChecked($this->__getLastVisitedLocation())); $this->__resetLastVisitedLocation(); } - + public function selected() { Expectations::shouldEqual($this->__getSelenium()->getValue($this->__getLastVisitedLocation()), $this->__getSelenium()->getSelectedLabel($this->__getLastVisitedLocation()."/..")); $this->__resetLastVisitedLocation(); } public function shouldBeOnPage($expected_url) { Expectations::shouldEqual($this->__getSelenium()->getLocation(), $expected_url); } - + } - + ?> \ No newline at end of file
xto/SUTA
a585d8a1703569c1b939a3ad2d16cfeb01c9c0ae
Fixed destroy sequence,updated package/xml to reflect the refactoring
diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php index 20fb299..4ca3c80 100644 --- a/expectations/ExpectationsSuite.php +++ b/expectations/ExpectationsSuite.php @@ -1,42 +1,41 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; require_once 'expectations/ExpectationsExpectations.php'; require_once 'expectations/TestSubjectExpectations.php'; require_once 'selenium_expectations/SeleniumDrivenUserExpectations.php'; class ExpectationsSuite { public static function suite() { $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); $suite->addTestSuite('ExpectationsExpectations'); $suite->addTestSuite('TestSubjectExpectations'); - //$suite->addTestSuite('SeleniumTestSubjectExpectations'); - - return $suite; + $suite->addTestSuite('SeleniumDrivenUserExpectations'); + return $suite; } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php index 90876ca..ebdd3a2 100644 --- a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -1,164 +1,164 @@ <?php require_once 'src/selenium_helper/SeleniumDrivenUser.php'; require_once 'src/selenium_helper/SeleniumExecutionContext.php'; class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase { private static $selenium_execution_context; private static $selenium_driven_user; public static function setUpBeforeClass() { - self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file:///home/nick/workspacePHP/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); } public static function tearDownAfterClass() { self::$selenium_driven_user->destroy(); } public function setUp() { - self::$selenium_driven_user->goesTo("file:///home/nick/workspacePHP/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + self::$selenium_driven_user->goesTo("file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { self::$selenium_driven_user->clicks("//input[@name='test_radio']"); self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { self::$selenium_driven_user->selects("Option")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { self::$selenium_driven_user->selects("Option 2")->from("test_select"); self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } } ?> \ No newline at end of file diff --git a/index.html b/index.html index cddb3b2..8715339 100644 --- a/index.html +++ b/index.html @@ -1,83 +1,94 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>xto/SUTA @ GitHub</title> <style type="text/css"> body { margin-top: 1.0em; background-color: FFFFFF; font-family: "Helvetica,Arial,FreeSans"; } #container { margin: 0 auto; width: 700px; } h1 { font-size: 3.8em; color: #FFFFFF; margin-bottom: 3px; background-color:#333333;} h1 .small { font-size: 0.4em; background-color:#333333;} h1 a { text-decoration: none;background-color:#333333;color:#FFFFFF } h2 { font-size: 1.5em; color: #FFFFFF;background-color:#333333 } h3 { text-align: center; color: #FFFFFF; background-color:#333333} .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} .download { float: right; } pre { background: #000; color: #fff; padding: 15px;} hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} .footer { text-align:center; padding-top:30px; font-style: italic; } </style> </head> <body> <a href="http://github.com/xto/SUTA"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> <div id="container"> <div class="download"> <a href="http://github.com/xto/SUTA/zipball/master"> <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a> <a href="http://github.com/xto/SUTA/tarball/master"> <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a> </div> <h1><a href="http://github.com/xto/SUTA">SUTA</a> <br /> <span class="small">by <a href="http://github.com/xto">Xavier To, Nicholas Lemay and Francis Falardeau</a></span></h1> <div class="description"> Simplified Unit Testing Add-on for phpunit </div> <h2>Dependencies</h2> <p>PHPUnit and Testing_Selenium</p> <h2>License</h2> <p>GPL</p> <h2>Authors</h2> -<p>nicholaslemay ([email protected]) <br/>Xavier Tô ([email protected]) <br/> <br/> </p> +<p>Nicholas Lemay ([email protected])<br/>Xavier Tô ([email protected])<br/>Francis Falardeau ([email protected])<br/><br /> </p> <h2>Contact</h2> -<p>Xavier Tô ([email protected]) <br/> </p> +<p>Xavier Tô ([email protected])<br/> </p> <h2>Download</h2> <p> You can download this project in either <a href="http://github.com/xto/SUTA/zipball/master">zip</a> or <a href="http://github.com/xto/SUTA/tarball/master">tar</a> formats. </p> <p>You can also clone the project with <a href="http://git-scm.com">Git</a> by running: <pre>$ git clone git://github.com/xto/SUTA</pre> </p> + + <h2>Installation</h2> + <p>There's 2 ways to install SUTA. You can pull the code from the repository and just include the files in your project. + However this solution isn't as practical since you'll need to include the files in every project you which to use SUTA. + The other way to install it is just to pull the code, move the package.xml file out of the SUTA folder and package it with PEAR and install it + with the following commands :<br /><br /> + <code> + pear package<br /> + sudo pear install SUTA-0.1.tgz + </code> + </p> <div class="footer"> get the source code on GitHub : <a href="http://github.com/xto/SUTA">xto/SUTA</a> </div> </div> </body> </html> diff --git a/package.xml b/package.xml index a3ae139..ca8fa12 100644 --- a/package.xml +++ b/package.xml @@ -1,57 +1,60 @@ <?xml version="1.0" encoding="UTF-8"?> -<package packagerversion="0.1" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> +<package packagerversion="0.1.1" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> <name>SUTA</name> <channel>pear.php.net</channel> <summary>DSL for PHPUnit and Selenium</summary> <description>Simplfied Unit Test Addon for PHPUnit that allow a natural language syntax</description> <lead> <name>Xavier Tô</name> <user>xto</user> <email>[email protected]</email> <active>yes</active> </lead> <lead> <name>nicholas Lemay</name> <user>nichoalslemay</user> <email>[email protected]</email> <active>yes</active> </lead> <lead> <name>Francis Falardeau</name> <user>ffalardeau</user> <email>[email protected]</email> <active>yes</active> </lead> - <date>2010-02-09</date> - <time>15:04:34</time> + <date>2010-02-16</date> + <time>23:00:00</time> <version> - <release>0.1</release> - <api>0.1</api> + <release>0.1.1</release> + <api>0.1.1</api> </version> <stability> <release>beta</release> <api>beta</api> </stability> <license>GPL</license> <notes> http://github.com/xto/SUTA </notes> <contents> <dir name="/"> <file name="/SUTA/src/Expectations.php" role="php" /> <file name="/SUTA/src/TestSubject.php" role="php" /> - <file name="/SUTA/src/selenium_helper/SeleniumTestSubject.php" role="php" /> + <file name="/SUTA/src/selenium_helper/SeleniumDrivenUser.php" role="php" /> + <file name="/SUTA/src/selenium_helper/SeleniumActions.php" role="php" /> + <file name="/SUTA/src/selenium_helper/SeleniumExecutionContext.php" role="php" /> + <file name="/SUTA/src/selenium_helper/SeleniumExpectations.php" role="php" /> </dir> </contents> <dependencies> <required> <php> <min>5.2.9</min> </php> <pearinstaller> <min>1.9.0</min> </pearinstaller> </required> </dependencies> <phprelease /> </package> diff --git a/src/selenium_helper/SeleniumDrivenUser.php b/src/selenium_helper/SeleniumDrivenUser.php index b0724c6..745f78d 100644 --- a/src/selenium_helper/SeleniumDrivenUser.php +++ b/src/selenium_helper/SeleniumDrivenUser.php @@ -1,51 +1,49 @@ <?php require_once 'Testing/Selenium.php'; require_once dirname(__FILE__).'/../Expectations.php'; require_once dirname(__FILE__).'/SeleniumActions.php'; require_once dirname(__FILE__).'/SeleniumExpectations.php'; class SeleniumDrivenUser { private $__seleniumExecutionContext; private $__seleniumActions; private $__seleniumExpectations; public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext = $seleniumExecutionContext; $this->__seleniumActions = new SeleniumActions($this->__seleniumExecutionContext); $this->__seleniumExpectations = new SeleniumExpectations($this->__seleniumExecutionContext); $this->__seleniumExecutionContext->initialize(); - - } public function destroy() { $this->__seleniumExecutionContext->destroy(); } function __call($method_name, $args) { if(method_exists($this->__seleniumActions, $method_name)) { call_user_func_array( array($this->__seleniumActions, $method_name), $args); return $this; } else if(method_exists(SeleniumExpectations, $method_name)) { call_user_func_array( array($this->__seleniumExpectations, $method_name), $args); return $this; } else { throw new Exception('Unknown method '.$method_name."called on ".get_class($this)." instance."); } } } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExecutionContext.php b/src/selenium_helper/SeleniumExecutionContext.php index cd2b397..6609927 100644 --- a/src/selenium_helper/SeleniumExecutionContext.php +++ b/src/selenium_helper/SeleniumExecutionContext.php @@ -1,75 +1,75 @@ <?php class SeleniumExecutionContext { private $__browser; private $__website; private $__selenium; private $__isInitialized; private $__lastVisitedLocation; public function __construct($browser, $website) { $this->__browser = $browser; $this->__website = $website; $this->__selenium = new Testing_Selenium($browser, $website); $this->__isInitialized = false; $this->resetLastVisitedLocation(); } public function getBrowser() { return $this->__browser; } public function getWebSite() { return $this->__website; } public function getSelenium() { return $this->__selenium; } public function setLastVisitedLocation($location) { $this->__lastVisitedLocation = $location; } public function getLastVisitedLocation() { return $this->__lastVisitedLocation; } public function resetLastVisitedLocation() { $this->__lastVisitedLocation = null; } public function initialize() { if(!$this->__isInitialized) $this->__startSelenium(); } public function destroy() { if($this->__isInitialized) $this->__stopSelenium(); } private function __startSelenium() { $this->__selenium->start(); - $this->__isStarted = true; + $this->__isInitialized = true; } private function __stopSelenium() { $this->__selenium->close(); $this->__selenium->stop(); } } ?> \ No newline at end of file
xto/SUTA
8b3c897e6157fe8ea1571075919531c423f1faf5
Corrected typo.
diff --git a/src/selenium_helper/SeleniumActions.php b/src/selenium_helper/SeleniumActions.php index c5181b0..5420492 100644 --- a/src/selenium_helper/SeleniumActions.php +++ b/src/selenium_helper/SeleniumActions.php @@ -1,96 +1,96 @@ <?php class SeleniumActions { private $__seleniumExecutionContext; public function __construct($seleniumExecutionContext) { $this->__seleniumExecutionContext= $seleniumExecutionContext; } private function __getLastVisitedLocation() { return $this->__seleniumExecutionContext->getLastVisitedLocation(); } private function __getSelenium() { return $this->__seleniumExecutionContext->getSelenium(); } private function __setLastVisitedLocation($location) { $this->__seleniumExecutionContext->setLastVisitedLocation($location); } private function __resetLastVisitedLocation() { $this->__seleniumExecutionContext->resetLastVisitedLocation(); } public function goesTo($url) { $this->__getSelenium()->open($url); } public function fillsOut($text_field_locator) { $this->__setLastVisitedLocation($text_field_locator); } public function with($value) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to type... Please specify where to type."); $this->__getSelenium()->type($this->__getLastVisitedLocation(), $value); $this->__resetLastVisitedLocation(); } public function clicks($locator) { $this->__getSelenium()->click($locator); } public function and_then() { } public function waitsForPageToLoad() { $this->__getSelenium()->waitForPageToLoad(30000); } public function drags($objects_locator) { $this->__setLastVisitedLocation($objects_locator); } public function dropsOn($destinations_locator) { Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to drop... Please specify where to drop the object."); $this->__getSelenium()->dragAndDropToObject($this->__getLastVisitedLocation(),$destinations_locator); } public function checks($checkbox_or_radio_button_locator) { $this->clicks($checkbox_or_radio_button_locator); } public function selects($value) { $this->__setLastVisitedLocation($value); } public function from($dropdown_list_locator) { - Expectations::shouldNotBeNull($this->__getLastVisitedLocation,"Nowhere to pick from... Please specify where to find the selection."); + Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to pick from... Please specify where to find the selection."); $this->__getSelenium()->select($dropdown_list_locator,'label='.$this->__getLastVisitedLocation()); $this->__resetLastVisitedLocation(); } } ?> \ No newline at end of file
xto/SUTA
5a37c588ddae64bc8657ca4d3b5cf5abaa0f8ace
Major refactoring of methods to split concerns in different classes.
diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php index 5d5eb32..20fb299 100644 --- a/expectations/ExpectationsSuite.php +++ b/expectations/ExpectationsSuite.php @@ -1,42 +1,42 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; require_once 'expectations/ExpectationsExpectations.php'; require_once 'expectations/TestSubjectExpectations.php'; - require_once 'selenium_expectations/SeleniumTestSubjectExpectations.php'; + require_once 'selenium_expectations/SeleniumDrivenUserExpectations.php'; class ExpectationsSuite { public static function suite() { $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); $suite->addTestSuite('ExpectationsExpectations'); $suite->addTestSuite('TestSubjectExpectations'); //$suite->addTestSuite('SeleniumTestSubjectExpectations'); return $suite; } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php new file mode 100644 index 0000000..90876ca --- /dev/null +++ b/expectations/selenium_expectations/SeleniumDrivenUserExpectations.php @@ -0,0 +1,164 @@ +<?php + + require_once 'src/selenium_helper/SeleniumDrivenUser.php'; + require_once 'src/selenium_helper/SeleniumExecutionContext.php'; + class SeleniumDrivenUserExpectations extends PHPUnit_Framework_TestCase + { + private static $selenium_execution_context; + private static $selenium_driven_user; + + public static function setUpBeforeClass() + { + self::$selenium_execution_context = new SeleniumExecutionContext("firefox","file:///home/nick/workspacePHP/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + self::$selenium_driven_user = new SeleniumDrivenUser(self::$selenium_execution_context); + } + + public static function tearDownAfterClass() + { + self::$selenium_driven_user->destroy(); + } + + public function setUp() + { + self::$selenium_driven_user->goesTo("file:///home/nick/workspacePHP/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + } + + /** + * @test + */ + public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() + { + try + { + self::$selenium_driven_user->shouldSee("id('non_existant_id')"); + self::fail("shouldSee should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function shouldSeeShouldSucceedWhenElementIsFound() + { + self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); + } + + /** + * @test + */ + public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() + { + try + { + self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); + self::fail("withText should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function withTextShouldSucceedIfTextMatchesParameter() + { + self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); + } + + /** + * @test + */ + public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() + { + try + { + self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); + self::fail("checked should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() + { + self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); + self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); + + } + + /** + * @test + */ + public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() + { + self::$selenium_driven_user->clicks("//input[@name='test_radio']"); + self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); + + } + + /** + * @test + */ + public function checkedShouldFailIfElementIsAnUncheckedCheckbox() + { + try + { + self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); + self::fail("checked should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() + { + try + { + self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); + self::fail("checked should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function selectedFailWhenOptionDoesNotExist() + { + try + { + self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); + self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); + self::fail("selected should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function selectedFailWhenOptionIsNotSelected() + { + try + { + self::$selenium_driven_user->selects("Option")->from("test_select"); + self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); + self::fail("selected should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function selectedShouldSucceedWhenOptionIsSelected() + { + self::$selenium_driven_user->selects("Option 2")->from("test_select"); + self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); + } + } +?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumActions.php b/src/selenium_helper/SeleniumActions.php index 92cae8a..c5181b0 100644 --- a/src/selenium_helper/SeleniumActions.php +++ b/src/selenium_helper/SeleniumActions.php @@ -1,74 +1,96 @@ <?php - class SeleniumActions - { - public function goesTo($url) - { - $this->selenium->open($url); - return $this; - } - - public function fillsOut($text_field_locator) - { - $this->lastKnownLocator = $text_field_locator; - return $this; - } - - public function with($value) - { - Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to type... Please specify where to type."); - $this->selenium->type($this->lastKnownLocator,$value); - $this->lastKnownLocator = null; - return $this; - } - - public function clicks($locator) - { - $this->selenium->click($locator); - return $this; - } - - public function and_then() - { - return $this; - } - - public function waitsForPageToLoad() - { - $this->selenium->waitForPageToLoad(30000); - } - - public function drags($objects_locator) - { - $this->lastKnownLocator = $locator; - return $this; - } - - public function dropsOn($destinations_locator) - { - Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to drop... Please specify where to drop the object."); - $this->selenium->dragAndDropToObject($this->lastKnownLocator,$destinations_locator); - return $this; - } - - public function checks($checkbox_or_radio_button_locator) - { - return $this->clicks($checkbox_or_radio_button_locator); - } - - public function selects($value) - { - $this->lastKnownLocator = $value; - return $this; - } - - public function from($dropdown_list_locator) - { - Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to pick from... Please specify where to find the selection."); - $this->selenium->select($dropdown_list_locator,'label='.$this->lastKnownLocator); - $this->lastKnownLocator = null; - } - - - } + + class SeleniumActions + { + private $__seleniumExecutionContext; + + public function __construct($seleniumExecutionContext) + { + $this->__seleniumExecutionContext= $seleniumExecutionContext; + } + + private function __getLastVisitedLocation() + { + return $this->__seleniumExecutionContext->getLastVisitedLocation(); + } + + private function __getSelenium() + { + return $this->__seleniumExecutionContext->getSelenium(); + } + + private function __setLastVisitedLocation($location) + { + $this->__seleniumExecutionContext->setLastVisitedLocation($location); + } + + private function __resetLastVisitedLocation() + { + $this->__seleniumExecutionContext->resetLastVisitedLocation(); + } + + public function goesTo($url) + { + $this->__getSelenium()->open($url); + } + + public function fillsOut($text_field_locator) + { + $this->__setLastVisitedLocation($text_field_locator); + } + + public function with($value) + { + Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to type... Please specify where to type."); + $this->__getSelenium()->type($this->__getLastVisitedLocation(), $value); + $this->__resetLastVisitedLocation(); + } + + public function clicks($locator) + { + $this->__getSelenium()->click($locator); + } + + public function and_then() + { + } + + public function waitsForPageToLoad() + { + $this->__getSelenium()->waitForPageToLoad(30000); + } + + public function drags($objects_locator) + { + $this->__setLastVisitedLocation($objects_locator); + } + + public function dropsOn($destinations_locator) + { + Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"Nowhere to drop... Please specify where to drop the object."); + $this->__getSelenium()->dragAndDropToObject($this->__getLastVisitedLocation(),$destinations_locator); + } + + public function checks($checkbox_or_radio_button_locator) + { + $this->clicks($checkbox_or_radio_button_locator); + } + + public function selects($value) + { + $this->__setLastVisitedLocation($value); + } + + public function from($dropdown_list_locator) + { + Expectations::shouldNotBeNull($this->__getLastVisitedLocation,"Nowhere to pick from... Please specify where to find the selection."); + $this->__getSelenium()->select($dropdown_list_locator,'label='.$this->__getLastVisitedLocation()); + $this->__resetLastVisitedLocation(); + } + + + + } + ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumDrivenUser.php b/src/selenium_helper/SeleniumDrivenUser.php index fa2c667..b0724c6 100644 --- a/src/selenium_helper/SeleniumDrivenUser.php +++ b/src/selenium_helper/SeleniumDrivenUser.php @@ -1,53 +1,51 @@ <?php - require_once 'Testing/Selenium.php'; + + require_once 'Testing/Selenium.php'; require_once dirname(__FILE__).'/../Expectations.php'; + require_once dirname(__FILE__).'/SeleniumActions.php'; + require_once dirname(__FILE__).'/SeleniumExpectations.php'; + class SeleniumDrivenUser { + + private $__seleniumExecutionContext; + private $__seleniumActions; + private $__seleniumExpectations; - private $selenium; - private $lastKnownLocator; - - public function __construct($browser,$website) + public function __construct($seleniumExecutionContext) { - $this->selenium = new Testing_Selenium($browser,$website); - $this->selenium->start(); - return $this; + $this->__seleniumExecutionContext = $seleniumExecutionContext; + $this->__seleniumActions = new SeleniumActions($this->__seleniumExecutionContext); + $this->__seleniumExpectations = new SeleniumExpectations($this->__seleniumExecutionContext); + $this->__seleniumExecutionContext->initialize(); + + } - + public function destroy() { - $this->selenium->close(); - $this->selenium->stop(); + $this->__seleniumExecutionContext->destroy(); } - + function __call($method_name, $args) { - if(method_exists($this->__subject, $method_name)) - { - return new SeleniumTestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); - } - else if(method_exists(SeleniumActions, $method_name)) + if(method_exists($this->__seleniumActions, $method_name)) { - array_unshift($args,$this->__subject); - return call_user_func_array( array(SeleniumActions, $method_name), $args); + call_user_func_array( array($this->__seleniumActions, $method_name), $args); + return $this; } - else if(methods_exists(SeleniumExpectations,$method_name)) + else if(method_exists(SeleniumExpectations, $method_name)) { - array_unshift($args,$this->__subject); - return call_user_func_array( array(SeleniumExpectations, $method_name), $args); + call_user_func_array( array($this->__seleniumExpectations, $method_name), $args); + return $this; } else { - throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); + throw new Exception('Unknown method '.$method_name."called on ".get_class($this)." instance."); } } - /** - * Actions - */ - /** - * Expectations - */ + } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExecutionContext.php b/src/selenium_helper/SeleniumExecutionContext.php new file mode 100644 index 0000000..cd2b397 --- /dev/null +++ b/src/selenium_helper/SeleniumExecutionContext.php @@ -0,0 +1,75 @@ +<?php + + class SeleniumExecutionContext + { + private $__browser; + private $__website; + private $__selenium; + private $__isInitialized; + private $__lastVisitedLocation; + + public function __construct($browser, $website) + { + $this->__browser = $browser; + $this->__website = $website; + $this->__selenium = new Testing_Selenium($browser, $website); + $this->__isInitialized = false; + $this->resetLastVisitedLocation(); + } + + public function getBrowser() + { + return $this->__browser; + } + + public function getWebSite() + { + return $this->__website; + } + + public function getSelenium() + { + return $this->__selenium; + } + + public function setLastVisitedLocation($location) + { + $this->__lastVisitedLocation = $location; + } + + public function getLastVisitedLocation() + { + return $this->__lastVisitedLocation; + } + + public function resetLastVisitedLocation() + { + $this->__lastVisitedLocation = null; + } + + public function initialize() + { + if(!$this->__isInitialized) + $this->__startSelenium(); + } + + public function destroy() + { + if($this->__isInitialized) + $this->__stopSelenium(); + } + + private function __startSelenium() + { + $this->__selenium->start(); + $this->__isStarted = true; + } + + private function __stopSelenium() + { + $this->__selenium->close(); + $this->__selenium->stop(); + } + + } +?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExpectations.php b/src/selenium_helper/SeleniumExpectations.php index c92fbb7..9ed5d3d 100644 --- a/src/selenium_helper/SeleniumExpectations.php +++ b/src/selenium_helper/SeleniumExpectations.php @@ -1,37 +1,64 @@ <?php class SeleniumExpectations { + + private $__seleniumExecutionContext; + + public function __construct($seleniumExecutionContext) + { + $this->__seleniumExecutionContext= $seleniumExecutionContext; + } + + private function __getLastVisitedLocation() + { + return $this->__seleniumExecutionContext->getLastVisitedLocation(); + } + + private function __getSelenium() + { + return $this->__seleniumExecutionContext->getSelenium(); + } + + private function __resetLastVisitedLocation() + { + $this->__seleniumExecutionContext->resetLastVisitedLocation(); + } + + private function __setLastVisitedLocation($location) + { + $this->__seleniumExecutionContext->setLastVisitedLocation($location); + } + public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ - Expectations::shouldBeTrue($this->selenium->isElementPresent($element_locator),$message ); - $this->lastKnownLocator = $element_locator; - return $this; + Expectations::shouldBeTrue($this->__getSelenium()->isElementPresent($element_locator),$message ); + $this->__setLastVisitedLocation($element_locator); } public function withText($expected_text) { - Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); - Expectations::shouldContain($expected_text,$this->selenium->getText($this->lastKnownLocator)); - $this->lastKnownLocator = null; + Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); + Expectations::shouldContain($expected_text,$this->__getSelenium()->getText($this->__getLastVisitedLocation())); + $this->__resetLastVisitedLocation(); } public function checked() { - Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); - Expectations::shouldBeTrue($this->selenium->isChecked($this->lastKnownLocator)); - $this->lastKnownLocator = null; + Expectations::shouldNotBeNull($this->__getLastVisitedLocation(),"No element was specified. Did you forget the call to shouldSee ?"); + Expectations::shouldBeTrue($this->__getSelenium()->isChecked($this->__getLastVisitedLocation())); + $this->__resetLastVisitedLocation(); } public function selected() { - Expectations::shouldEqual($this->selenium->getValue($this->lastKnownLocator), $this->selenium->getSelectedLabel($this->lastKnownLocator."/..")); - $this->lastKnownLocator = null; + Expectations::shouldEqual($this->__getSelenium()->getValue($this->__getLastVisitedLocation()), $this->__getSelenium()->getSelectedLabel($this->__getLastVisitedLocation()."/..")); + $this->__resetLastVisitedLocation(); } public function shouldBeOnPage($expected_url) { - Expectations::shouldEqual($this->selenium->getLocation(), $expected_url); + Expectations::shouldEqual($this->__getSelenium()->getLocation(), $expected_url); } } ?> \ No newline at end of file
xto/SUTA
89c55cbaec1b8386a2b7a5ca8c2c949453d51aaa
Partial refactor... not working yet
diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php index 504e583..5d5eb32 100644 --- a/expectations/ExpectationsSuite.php +++ b/expectations/ExpectationsSuite.php @@ -1,42 +1,42 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; require_once 'expectations/ExpectationsExpectations.php'; require_once 'expectations/TestSubjectExpectations.php'; require_once 'selenium_expectations/SeleniumTestSubjectExpectations.php'; class ExpectationsSuite { public static function suite() { $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); $suite->addTestSuite('ExpectationsExpectations'); $suite->addTestSuite('TestSubjectExpectations'); - $suite->addTestSuite('SeleniumTestSubjectExpectations'); + //$suite->addTestSuite('SeleniumTestSubjectExpectations'); return $suite; } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php b/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php index 638c413..9bb5da8 100644 --- a/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php +++ b/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php @@ -1,162 +1,162 @@ <?php - require_once 'src/selenium_helper/SeleniumTestSubject.php'; + require_once 'src/selenium_helper/SeleniumDrivenUser.php'; class SeleniumTestSubjectExpectations extends PHPUnit_Framework_TestCase { - private static $selenium_test_subject; + private static $selenium_driven_user; public static function setUpBeforeClass() { - self::$selenium_test_subject = new SeleniumTestSubject("firefox","file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + self::$selenium_driven_user = new SeleniumDrivenUser("firefox","file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); } public static function tearDownAfterClass() { - self::$selenium_test_subject->destroy(); + self::$selenium_driven_user->destroy(); } public function setUp() { - self::$selenium_test_subject->goesTo("file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + self::$selenium_driven_user->goesTo("file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); } /** * @test */ public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() { try { - self::$selenium_test_subject->shouldSee("id('non_existant_id')"); + self::$selenium_driven_user->shouldSee("id('non_existant_id')"); self::fail("shouldSee should have failed"); } catch(Exception $e){} } /** * @test */ public function shouldSeeShouldSucceedWhenElementIsFound() { - self::$selenium_test_subject->shouldSee("//*[id('test_span')]"); + self::$selenium_driven_user->shouldSee("//*[id('test_span')]"); } /** * @test */ public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() { try { - self::$selenium_test_subject->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); + self::$selenium_driven_user->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); self::fail("withText should have failed"); } catch(Exception $e){} } /** * @test */ public function withTextShouldSucceedIfTextMatchesParameter() { - self::$selenium_test_subject->shouldSee("//span[id('test_span')]")->withText("Text"); + self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->withText("Text"); } /** * @test */ public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() { try { - self::$selenium_test_subject->shouldSee("//span[id('test_span')]")->checked(); + self::$selenium_driven_user->shouldSee("//span[id('test_span')]")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() { - self::$selenium_test_subject->clicks("//input[@name='test_checkbox']"); - self::$selenium_test_subject->shouldSee("//input[@name='test_checkbox']")->checked(); + self::$selenium_driven_user->clicks("//input[@name='test_checkbox']"); + self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); } /** * @test */ public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() { - self::$selenium_test_subject->clicks("//input[@name='test_radio']"); - self::$selenium_test_subject->shouldSee("//input[@name='test_radio']")->checked(); + self::$selenium_driven_user->clicks("//input[@name='test_radio']"); + self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedCheckbox() { try { - self::$selenium_test_subject->shouldSee("//input[@name='test_checkbox']")->checked(); + self::$selenium_driven_user->shouldSee("//input[@name='test_checkbox']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() { try { - self::$selenium_test_subject->shouldSee("//input[@name='test_radio']")->checked(); + self::$selenium_driven_user->shouldSee("//input[@name='test_radio']")->checked(); self::fail("checked should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionDoesNotExist() { try { - self::$selenium_test_subject->selects("Unknown Option")->from("test_select"); - self::$selenium_test_subject->shouldSee("//select/option[2]")->selected(); + self::$selenium_driven_user->selects("Unknown Option")->from("test_select"); + self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedFailWhenOptionIsNotSelected() { try { - self::$selenium_test_subject->selects("Option")->from("test_select"); - self::$selenium_test_subject->shouldSee("//select/option[1]")->selected(); + self::$selenium_driven_user->selects("Option")->from("test_select"); + self::$selenium_driven_user->shouldSee("//select/option[1]")->selected(); self::fail("selected should have failed"); } catch(Exception $e){} } /** * @test */ public function selectedShouldSucceedWhenOptionIsSelected() { - self::$selenium_test_subject->selects("Option 2")->from("test_select"); - self::$selenium_test_subject->shouldSee("//select/option[2]")->selected(); + self::$selenium_driven_user->selects("Option 2")->from("test_select"); + self::$selenium_driven_user->shouldSee("//select/option[2]")->selected(); } } ?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumActions.php b/src/selenium_helper/SeleniumActions.php new file mode 100644 index 0000000..92cae8a --- /dev/null +++ b/src/selenium_helper/SeleniumActions.php @@ -0,0 +1,74 @@ +<?php + class SeleniumActions + { + public function goesTo($url) + { + $this->selenium->open($url); + return $this; + } + + public function fillsOut($text_field_locator) + { + $this->lastKnownLocator = $text_field_locator; + return $this; + } + + public function with($value) + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to type... Please specify where to type."); + $this->selenium->type($this->lastKnownLocator,$value); + $this->lastKnownLocator = null; + return $this; + } + + public function clicks($locator) + { + $this->selenium->click($locator); + return $this; + } + + public function and_then() + { + return $this; + } + + public function waitsForPageToLoad() + { + $this->selenium->waitForPageToLoad(30000); + } + + public function drags($objects_locator) + { + $this->lastKnownLocator = $locator; + return $this; + } + + public function dropsOn($destinations_locator) + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to drop... Please specify where to drop the object."); + $this->selenium->dragAndDropToObject($this->lastKnownLocator,$destinations_locator); + return $this; + } + + public function checks($checkbox_or_radio_button_locator) + { + return $this->clicks($checkbox_or_radio_button_locator); + } + + public function selects($value) + { + $this->lastKnownLocator = $value; + return $this; + } + + public function from($dropdown_list_locator) + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to pick from... Please specify where to find the selection."); + $this->selenium->select($dropdown_list_locator,'label='.$this->lastKnownLocator); + $this->lastKnownLocator = null; + } + + + + } +?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumDrivenUser.php b/src/selenium_helper/SeleniumDrivenUser.php new file mode 100644 index 0000000..fa2c667 --- /dev/null +++ b/src/selenium_helper/SeleniumDrivenUser.php @@ -0,0 +1,53 @@ +<?php + require_once 'Testing/Selenium.php'; + require_once dirname(__FILE__).'/../Expectations.php'; + class SeleniumDrivenUser + { + + private $selenium; + private $lastKnownLocator; + + public function __construct($browser,$website) + { + $this->selenium = new Testing_Selenium($browser,$website); + $this->selenium->start(); + return $this; + } + + public function destroy() + { + $this->selenium->close(); + $this->selenium->stop(); + } + + function __call($method_name, $args) + { + if(method_exists($this->__subject, $method_name)) + { + return new SeleniumTestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); + } + else if(method_exists(SeleniumActions, $method_name)) + { + array_unshift($args,$this->__subject); + return call_user_func_array( array(SeleniumActions, $method_name), $args); + } + else if(methods_exists(SeleniumExpectations,$method_name)) + { + array_unshift($args,$this->__subject); + return call_user_func_array( array(SeleniumExpectations, $method_name), $args); + } + else + { + throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); + } + } + + /** + * Actions + */ + /** + * Expectations + */ + + } +?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumExpectations.php b/src/selenium_helper/SeleniumExpectations.php new file mode 100644 index 0000000..c92fbb7 --- /dev/null +++ b/src/selenium_helper/SeleniumExpectations.php @@ -0,0 +1,37 @@ +<?php + class SeleniumExpectations + { + public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ + Expectations::shouldBeTrue($this->selenium->isElementPresent($element_locator),$message ); + $this->lastKnownLocator = $element_locator; + return $this; + } + + public function withText($expected_text) + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); + Expectations::shouldContain($expected_text,$this->selenium->getText($this->lastKnownLocator)); + $this->lastKnownLocator = null; + } + + public function checked() + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); + Expectations::shouldBeTrue($this->selenium->isChecked($this->lastKnownLocator)); + $this->lastKnownLocator = null; + } + + public function selected() + { + Expectations::shouldEqual($this->selenium->getValue($this->lastKnownLocator), $this->selenium->getSelectedLabel($this->lastKnownLocator."/..")); + $this->lastKnownLocator = null; + } + + public function shouldBeOnPage($expected_url) + { + Expectations::shouldEqual($this->selenium->getLocation(), $expected_url); + } + + } + +?> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumTestSubject.php b/src/selenium_helper/SeleniumTestSubject.php deleted file mode 100644 index efdd19c..0000000 --- a/src/selenium_helper/SeleniumTestSubject.php +++ /dev/null @@ -1,152 +0,0 @@ -<?php - require_once 'Testing/Selenium.php'; - require_once dirname(__FILE__).'/../Expectations.php'; - class SeleniumTestSubject - { - - private $selenium; - private $lastKnownLocator; - - - public function __construct($browser,$website) - { - $this->selenium = new Testing_Selenium($browser,$website); - $this->selenium->start(); - return $this; - } - - public function destroy() - { - $this->selenium->close(); - $this->selenium->stop(); - } - - function __call($method_name, $args) - { - if(method_exists($this->__subject, $method_name)) - { - return new SeleniumTestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); - } - else if(method_exists(SeleniumActions, $method_name)) - { - array_unshift($args,$this->__subject); - return call_user_func_array( array(SeleniumActions, $method_name), $args); - } - else if(methods_exists(SeleniumExpectations,$method_name)) - { - array_unshift($args,$this->__subject); - return call_user_func_array( array(SeleniumExpectations, $method_name), $args); - } - else - { - throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); - } - } - - /** - * Actions - */ - public function goesTo($url) - { - $this->selenium->open($url); - return $this; - } - - public function fillsOut($text_field_locator) - { - $this->lastKnownLocator = $text_field_locator; - return $this; - } - - public function with($value) - { - Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to type... Please specify where to type."); - $this->selenium->type($this->lastKnownLocator,$value); - $this->lastKnownLocator = null; - return $this; - } - - public function clicks($locator) - { - $this->selenium->click($locator); - return $this; - } - - public function and_then() - { - return $this; - } - - public function waitsForPageToLoad() - { - $this->selenium->waitForPageToLoad(30000); - } - - public function drags($objects_locator) - { - $this->lastKnownLocator = $locator; - return $this; - } - - public function dropsOn($destinations_locator) - { - Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to drop... Please specify where to drop the object."); - $this->selenium->dragAndDropToObject($this->lastKnownLocator,$destinations_locator); - return $this; - } - - public function checks($checkbox_or_radio_button_locator) - { - return $this->clicks($checkbox_or_radio_button_locator); - } - - public function selects($value) - { - $this->lastKnownLocator = $value; - return $this; - } - - public function from($dropdown_list_locator) - { - Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to pick from... Please specify where to find the selection."); - $this->selenium->select($dropdown_list_locator,'label='.$this->lastKnownLocator); - $this->lastKnownLocator = null; - } - - - /** - * Expectations - */ - public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ - Expectations::shouldBeTrue($this->selenium->isElementPresent($element_locator),$message ); - $this->lastKnownLocator = $element_locator; - return $this; - } - - public function withText($expected_text) - { - Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); - Expectations::shouldContain($expected_text,$this->selenium->getText($this->lastKnownLocator)); - $this->lastKnownLocator = null; - } - - public function checked() - { - Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); - Expectations::shouldBeTrue($this->selenium->isChecked($this->lastKnownLocator)); - $this->lastKnownLocator = null; - } - - public function selected() - { - Expectations::shouldEqual($this->selenium->getValue($this->lastKnownLocator), $this->selenium->getSelectedLabel($this->lastKnownLocator."/..")); - $this->lastKnownLocator = null; - } - - public function shouldBeOnPage($expected_url) - { - Expectations::shouldEqual($this->selenium->getLocation(), $expected_url); - } - - } -?> \ No newline at end of file
xto/SUTA
079075299a870ea88ce9bb205005333daddf03d8
Refactored the selenium test subject part 1
diff --git a/expectations/selenium_expectations/selenium_test_page.html b/expectations/selenium_expectations/selenium_test_page.html index c27f30c..304d042 100644 --- a/expectations/selenium_expectations/selenium_test_page.html +++ b/expectations/selenium_expectations/selenium_test_page.html @@ -1,22 +1,25 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <span id="test_span">Text</span> <br /> <label for='test_checkbox'>Checkbox</label><input name="test_checkbox" type="checkbox"/> <br /> <label for='test_radio'>Radio</label><input name="test_radio" type="radio"/> <br /> <label for=test_select">Select</label> <select id="test_select"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> +<br /> +<label for="test_textfield">Text field</label> +<input type="text" /> </body> </html> \ No newline at end of file diff --git a/src/selenium_helper/SeleniumTestSubject.php b/src/selenium_helper/SeleniumTestSubject.php index b6b8117..7cdd375 100644 --- a/src/selenium_helper/SeleniumTestSubject.php +++ b/src/selenium_helper/SeleniumTestSubject.php @@ -1,125 +1,148 @@ <?php require_once 'Testing/Selenium.php'; require_once dirname(__FILE__).'/../Expectations.php'; class SeleniumTestSubject { private $selenium; private $lastKnownLocator; public function __construct($browser,$website) { $this->selenium = new Testing_Selenium($browser,$website); $this->selenium->start(); return $this; } public function destroy() { $this->selenium->close(); $this->selenium->stop(); } + + function __call($method_name, $args) + { + if(method_exists($this->__subject, $method_name)) + { + return new SeleniumTestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); + } + else if(method_exists(SeleniumActions, $method_name)) + { + array_unshift($args,$this->__subject); + return call_user_func_array( array(SeleniumActions, $method_name), $args); + } + else if(methods_exists(SeleniumExpectations,$method_name)) + { + array_unshift($args,$this->__subject); + return call_user_func_array( array(SeleniumExpectations, $method_name), $args); + } + else + { + throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); + } + } + /** * Actions */ public function goesTo($url) { $this->selenium->open($url); return $this; } public function fillsOut($text_field_locator) { $this->lastKnownLocator = $text_field_locator; return $this; } public function with($value) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to type... Please specify where to type."); $this->selenium->type($this->lastKnownLocator,$value); $this->lastKnownLocator = null; return $this; } public function clicks($locator) { $this->selenium->click($locator); return $this; } public function and_then() { return $this; } public function waitsForPageToLoad() { $this->selenium->waitForPageToLoad(30000); } public function drags($objects_locator) { $this->lastKnownLocator = $locator; return $this; } public function dropsOn($destinations_locator) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to drop... Please specify where to drop the object."); $this->selenium->dragAndDropToObject($this->lastKnownLocator,$destinations_locator); return $this; } public function checks($checkbox_or_radio_button_locator) { return $this->clicks($checkbox_or_radio_button_locator); } public function selects($value) { $this->lastKnownLocator = $value; return $this; } public function from($dropdown_list_locator) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to pick from... Please specify where to find the selection."); $this->selenium->select($dropdown_list_locator,'label='.$this->lastKnownLocator); $this->lastKnownLocator = null; } /** * Expectations */ public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ Expectations::shouldBeTrue($this->selenium->isElementPresent($element_locator),$message ); $this->lastKnownLocator = $element_locator; return $this; } public function withText($expected_text) { Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldEqual($this->selenium->getText($this->lastKnownLocator), $expected_text); $this->lastKnownLocator = null; } public function checked() { Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldBeTrue($this->selenium->isChecked($this->lastKnownLocator)); $this->lastKnownLocator = null; } public function selected() { Expectations::shouldEqual($this->selenium->getValue($this->lastKnownLocator), $this->selenium->getSelectedLabel($this->lastKnownLocator."/..")); $this->lastKnownLocator = null; } } ?> \ No newline at end of file
xto/SUTA
0cd329f18d972b777173851e3336d145e0ca8d35
Changed the shouldEqual to shouldContain for withText
diff --git a/src/selenium_helper/SeleniumTestSubject.php b/src/selenium_helper/SeleniumTestSubject.php index c2cb7ed..0a6c733 100644 --- a/src/selenium_helper/SeleniumTestSubject.php +++ b/src/selenium_helper/SeleniumTestSubject.php @@ -1,129 +1,129 @@ <?php require_once 'Testing/Selenium.php'; require_once dirname(__FILE__).'/../Expectations.php'; class SeleniumTestSubject { private $selenium; private $lastKnownLocator; public function __construct($browser,$website) { $this->selenium = new Testing_Selenium($browser,$website); $this->selenium->start(); return $this; } public function destroy() { $this->selenium->close(); $this->selenium->stop(); } /** * Actions */ public function goesTo($url) { $this->selenium->open($url); return $this; } public function fillsOut($text_field_locator) { $this->lastKnownLocator = $text_field_locator; return $this; } public function with($value) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to type... Please specify where to type."); $this->selenium->type($this->lastKnownLocator,$value); $this->lastKnownLocator = null; return $this; } public function clicks($locator) { $this->selenium->click($locator); return $this; } public function and_then() { return $this; } public function waitsForPageToLoad() { $this->selenium->waitForPageToLoad(30000); } public function drags($objects_locator) { $this->lastKnownLocator = $locator; return $this; } public function dropsOn($destinations_locator) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to drop... Please specify where to drop the object."); $this->selenium->dragAndDropToObject($this->lastKnownLocator,$destinations_locator); return $this; } public function checks($checkbox_or_radio_button_locator) { return $this->clicks($checkbox_or_radio_button_locator); } public function selects($value) { $this->lastKnownLocator = $value; return $this; } public function from($dropdown_list_locator) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to pick from... Please specify where to find the selection."); $this->selenium->select($dropdown_list_locator,'label='.$this->lastKnownLocator); $this->lastKnownLocator = null; } /** * Expectations */ public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ Expectations::shouldBeTrue($this->selenium->isElementPresent($element_locator),$message ); $this->lastKnownLocator = $element_locator; return $this; } public function withText($expected_text) { Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); - Expectations::shouldEqual($this->selenium->getText($this->lastKnownLocator), $expected_text); + Expectations::shouldContain($expected_text,$this->selenium->getText($this->lastKnownLocator)); $this->lastKnownLocator = null; } public function checked() { Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldBeTrue($this->selenium->isChecked($this->lastKnownLocator)); $this->lastKnownLocator = null; } public function selected() { Expectations::shouldEqual($this->selenium->getValue($this->lastKnownLocator), $this->selenium->getSelectedLabel($this->lastKnownLocator."/..")); $this->lastKnownLocator = null; } public function shouldBeOnPage($expected_url) { Expectations::shouldEqual($this->selenium->getLocation(), $expected_url); } } ?> \ No newline at end of file
xto/SUTA
c14532e462ba9d65acbf93bc985211e8146f9a06
Added shouldContain expectation
diff --git a/src/Expectations.php b/src/Expectations.php index 2e8631e..d0db76e 100644 --- a/src/Expectations.php +++ b/src/Expectations.php @@ -1,52 +1,57 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; class Expectations extends PHPUnit_Framework_Assert { public static function shouldBeTrue($value, $message="") { self::assertThat($value, self::isTrue(), $message); } public static function shouldBeFalse($value, $message="") { self::assertThat($value, self::isFalse(), $message); } public static function shouldEqual($actual, $expected, $message = '') { self::assertEquals($expected, $actual, $message); } - public static function shouldBeNull($value, $message = '') + public static function shouldBeNull($value, $message = '') { self::assertNull($value, $message); } - public static function shouldNotBeNull($value, $message = '') + public static function shouldNotBeNull($value, $message = '') { self::assertNotNull($value, $message); } + + public static function shouldContain($pattern, $value, $message = '') + { + self::assertContains($pattern, $value, $message); + } } ?>
xto/SUTA
873925b630aadc0d6651053b8cf04ec85c43267b
Fixed a typo
diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php index 5d53e9a..534e1ba 100644 --- a/expectations/ExpectationsExpectations.php +++ b/expectations/ExpectationsExpectations.php @@ -1,155 +1,155 @@ <?php require_once 'src/Expectations.php'; class ExpectationsExpectations extends PHPUnit_Framework_TestCase { /** * @test */ public function ShouldBeTrueShouldBehaveJustLikeassertTrue() { Expectations::shouldBeTrue(true); self::assertTrue(true); try { self::assertTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeFalseShouldBehaveJustLikeassertFalse() { Expectations::shouldBeFalse(false); self::assertFalse(false); try { self::assertFalse(True); throw new Exception("assertFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeFalse(true); throw new Exception("shouldBeFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldEqualShouldBehaveLikeAssertEqual() { self::assertEquals("tom","tom"); Expectations::shouldEqual("tom","tom"); try { self::assertEquals("foo", "bar"); throw new Exception("assertEquals should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldEqual("foo", "bar"); throw new Exception("shouldEqual should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeNullShouldBehaveLikeAssertNull() { Expectations::shouldBeNull(null); self::assertNull(null); try { self::assertNull("Something that isn't null"); throw new Exception("assertNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeNull("Something that isn't null"); throw new Exception("shouldBeNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldNotBeNullShouldBehaveLikeAssertNotNull() { self::assertNotNull("Something not null"); Expectations::shouldNotBeNull("Something not null"); try { self::assertNotNull(null); throw new Exception("assertNotNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { - Expectations::shouldNotNull(null); + Expectations::shouldNotBeNull(null); throw new Exception("shoulNotdBeNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldContainShouldBehaveLikeAssertContains() { self::assertContains("tom","tom petty"); Expectations::shouldContain("tom", "tom petty"); } } ?> \ No newline at end of file
xto/SUTA
3755bb0c97b79b7ba0971ecbae3e07844bd6f724
Added small test for shouldContain expectation.
diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php index 32a6f03..5d53e9a 100644 --- a/expectations/ExpectationsExpectations.php +++ b/expectations/ExpectationsExpectations.php @@ -1,140 +1,155 @@ <?php require_once 'src/Expectations.php'; class ExpectationsExpectations extends PHPUnit_Framework_TestCase { /** * @test */ public function ShouldBeTrueShouldBehaveJustLikeassertTrue() { Expectations::shouldBeTrue(true); self::assertTrue(true); try { self::assertTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeFalseShouldBehaveJustLikeassertFalse() { Expectations::shouldBeFalse(false); self::assertFalse(false); try { self::assertFalse(True); throw new Exception("assertFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeFalse(true); throw new Exception("shouldBeFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ - public function ShouldEqualShouldBehaveLikeAsserEqual() + public function ShouldEqualShouldBehaveLikeAssertEqual() { self::assertEquals("tom","tom"); Expectations::shouldEqual("tom","tom"); try { self::assertEquals("foo", "bar"); throw new Exception("assertEquals should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldEqual("foo", "bar"); throw new Exception("shouldEqual should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } + /** + * @test + */ public function ShouldBeNullShouldBehaveLikeAssertNull() { Expectations::shouldBeNull(null); self::assertNull(null); try { self::assertNull("Something that isn't null"); throw new Exception("assertNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeNull("Something that isn't null"); throw new Exception("shouldBeNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } - + + /** + * @test + */ public function ShouldNotBeNullShouldBehaveLikeAssertNotNull() { self::assertNotNull("Something not null"); Expectations::shouldNotBeNull("Something not null"); try { self::assertNotNull(null); throw new Exception("assertNotNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldNotNull(null); throw new Exception("shoulNotdBeNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } - } + + /** + * @test + */ + public function ShouldContainShouldBehaveLikeAssertContains() + { + self::assertContains("tom","tom petty"); + Expectations::shouldContain("tom", "tom petty"); + } + } ?> \ No newline at end of file
xto/SUTA
6481e112ff7be659cb18cbb0aa5ebbafc33cee52
Added shouldBeOnPage($expected_url) function
diff --git a/src/selenium_helper/SeleniumTestSubject.php b/src/selenium_helper/SeleniumTestSubject.php index b6b8117..c2cb7ed 100644 --- a/src/selenium_helper/SeleniumTestSubject.php +++ b/src/selenium_helper/SeleniumTestSubject.php @@ -1,125 +1,129 @@ <?php require_once 'Testing/Selenium.php'; require_once dirname(__FILE__).'/../Expectations.php'; class SeleniumTestSubject { private $selenium; private $lastKnownLocator; public function __construct($browser,$website) { $this->selenium = new Testing_Selenium($browser,$website); $this->selenium->start(); return $this; } public function destroy() { $this->selenium->close(); $this->selenium->stop(); } /** * Actions */ public function goesTo($url) { $this->selenium->open($url); return $this; } public function fillsOut($text_field_locator) { $this->lastKnownLocator = $text_field_locator; return $this; } public function with($value) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to type... Please specify where to type."); $this->selenium->type($this->lastKnownLocator,$value); $this->lastKnownLocator = null; return $this; } public function clicks($locator) { $this->selenium->click($locator); return $this; } public function and_then() { return $this; } public function waitsForPageToLoad() { $this->selenium->waitForPageToLoad(30000); } public function drags($objects_locator) { $this->lastKnownLocator = $locator; return $this; } public function dropsOn($destinations_locator) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to drop... Please specify where to drop the object."); $this->selenium->dragAndDropToObject($this->lastKnownLocator,$destinations_locator); return $this; } public function checks($checkbox_or_radio_button_locator) { return $this->clicks($checkbox_or_radio_button_locator); } public function selects($value) { $this->lastKnownLocator = $value; return $this; } public function from($dropdown_list_locator) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to pick from... Please specify where to find the selection."); $this->selenium->select($dropdown_list_locator,'label='.$this->lastKnownLocator); $this->lastKnownLocator = null; } /** * Expectations */ public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ Expectations::shouldBeTrue($this->selenium->isElementPresent($element_locator),$message ); $this->lastKnownLocator = $element_locator; return $this; } public function withText($expected_text) { Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldEqual($this->selenium->getText($this->lastKnownLocator), $expected_text); $this->lastKnownLocator = null; } public function checked() { Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); Expectations::shouldBeTrue($this->selenium->isChecked($this->lastKnownLocator)); $this->lastKnownLocator = null; } public function selected() { Expectations::shouldEqual($this->selenium->getValue($this->lastKnownLocator), $this->selenium->getSelectedLabel($this->lastKnownLocator."/..")); $this->lastKnownLocator = null; } - + + public function shouldBeOnPage($expected_url) + { + Expectations::shouldEqual($this->selenium->getLocation(), $expected_url); + } } ?> \ No newline at end of file
xto/SUTA
7c61630221d6dbd7b185ec336b9d929f7fd9a892
added pear package info
diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..a3ae139 --- /dev/null +++ b/package.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8"?> +<package packagerversion="0.1" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> + <name>SUTA</name> + <channel>pear.php.net</channel> + <summary>DSL for PHPUnit and Selenium</summary> + <description>Simplfied Unit Test Addon for PHPUnit that allow a natural language syntax</description> + <lead> + <name>Xavier Tô</name> + <user>xto</user> + <email>[email protected]</email> + <active>yes</active> + </lead> + <lead> + <name>nicholas Lemay</name> + <user>nichoalslemay</user> + <email>[email protected]</email> + <active>yes</active> + </lead> + <lead> + <name>Francis Falardeau</name> + <user>ffalardeau</user> + <email>[email protected]</email> + <active>yes</active> +</lead> + <date>2010-02-09</date> + <time>15:04:34</time> + <version> + <release>0.1</release> + <api>0.1</api> + </version> + <stability> + <release>beta</release> + <api>beta</api> + </stability> + <license>GPL</license> + <notes> +http://github.com/xto/SUTA + </notes> + <contents> + <dir name="/"> + <file name="/SUTA/src/Expectations.php" role="php" /> + <file name="/SUTA/src/TestSubject.php" role="php" /> + <file name="/SUTA/src/selenium_helper/SeleniumTestSubject.php" role="php" /> + </dir> + </contents> + <dependencies> + <required> + <php> + <min>5.2.9</min> + </php> + <pearinstaller> + <min>1.9.0</min> + </pearinstaller> + </required> + </dependencies> + <phprelease /> + </package>
xto/SUTA
d366f0271e9e01d7b99cd46f6ea5f2603ad69568
Made the web site tolerable to the human eye.
diff --git a/index.html b/index.html index 5cf2733..cddb3b2 100644 --- a/index.html +++ b/index.html @@ -1,83 +1,83 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>xto/SUTA @ GitHub</title> <style type="text/css"> body { margin-top: 1.0em; background-color: FFFFFF; font-family: "Helvetica,Arial,FreeSans"; } #container { margin: 0 auto; width: 700px; } h1 { font-size: 3.8em; color: #FFFFFF; margin-bottom: 3px; background-color:#333333;} h1 .small { font-size: 0.4em; background-color:#333333;} h1 a { text-decoration: none;background-color:#333333;color:#FFFFFF } h2 { font-size: 1.5em; color: #FFFFFF;background-color:#333333 } h3 { text-align: center; color: #FFFFFF; background-color:#333333} .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} .download { float: right; } pre { background: #000; color: #fff; padding: 15px;} hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} .footer { text-align:center; padding-top:30px; font-style: italic; } </style> </head> <body> <a href="http://github.com/xto/SUTA"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> <div id="container"> <div class="download"> <a href="http://github.com/xto/SUTA/zipball/master"> <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a> <a href="http://github.com/xto/SUTA/tarball/master"> <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a> </div> - <h1><a href="http://github.com/xto/SUTA">SUTA</a> + <h1><a href="http://github.com/xto/SUTA">SUTA</a> <br /> <span class="small">by <a href="http://github.com/xto">Xavier To, Nicholas Lemay and Francis Falardeau</a></span></h1> <div class="description"> Simplified Unit Testing Add-on for phpunit </div> <h2>Dependencies</h2> <p>PHPUnit and Testing_Selenium</p> <h2>License</h2> <p>GPL</p> <h2>Authors</h2> <p>nicholaslemay ([email protected]) <br/>Xavier Tô ([email protected]) <br/> <br/> </p> <h2>Contact</h2> <p>Xavier Tô ([email protected]) <br/> </p> <h2>Download</h2> <p> You can download this project in either <a href="http://github.com/xto/SUTA/zipball/master">zip</a> or <a href="http://github.com/xto/SUTA/tarball/master">tar</a> formats. </p> <p>You can also clone the project with <a href="http://git-scm.com">Git</a> by running: <pre>$ git clone git://github.com/xto/SUTA</pre> </p> <div class="footer"> get the source code on GitHub : <a href="http://github.com/xto/SUTA">xto/SUTA</a> </div> </div> </body> </html> diff --git a/index.html~ b/index.html~ new file mode 100644 index 0000000..5cf2733 --- /dev/null +++ b/index.html~ @@ -0,0 +1,83 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + + <title>xto/SUTA @ GitHub</title> + + <style type="text/css"> + body { + margin-top: 1.0em; + background-color: FFFFFF; + font-family: "Helvetica,Arial,FreeSans"; + + } + #container { + margin: 0 auto; + width: 700px; + } + h1 { font-size: 3.8em; color: #FFFFFF; margin-bottom: 3px; background-color:#333333;} + h1 .small { font-size: 0.4em; background-color:#333333;} + h1 a { text-decoration: none;background-color:#333333;color:#FFFFFF } + h2 { font-size: 1.5em; color: #FFFFFF;background-color:#333333 } + h3 { text-align: center; color: #FFFFFF; background-color:#333333} + .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} + .download { float: right; } + pre { background: #000; color: #fff; padding: 15px;} + hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} + .footer { text-align:center; padding-top:30px; font-style: italic; } + </style> + +</head> + +<body> + <a href="http://github.com/xto/SUTA"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> + + <div id="container"> + + <div class="download"> + <a href="http://github.com/xto/SUTA/zipball/master"> + <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a> + <a href="http://github.com/xto/SUTA/tarball/master"> + <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a> + </div> + + <h1><a href="http://github.com/xto/SUTA">SUTA</a> + <span class="small">by <a href="http://github.com/xto">Xavier To, Nicholas Lemay and Francis Falardeau</a></span></h1> + + <div class="description"> + Simplified Unit Testing Add-on for phpunit + </div> + + <h2>Dependencies</h2> +<p>PHPUnit and Testing_Selenium</p> +<h2>License</h2> +<p>GPL</p> +<h2>Authors</h2> +<p>nicholaslemay ([email protected]) <br/>Xavier Tô ([email protected]) <br/> <br/> </p> +<h2>Contact</h2> +<p>Xavier Tô ([email protected]) <br/> </p> + + + <h2>Download</h2> + <p> + You can download this project in either + <a href="http://github.com/xto/SUTA/zipball/master">zip</a> or + <a href="http://github.com/xto/SUTA/tarball/master">tar</a> formats. + </p> + <p>You can also clone the project with <a href="http://git-scm.com">Git</a> + by running: + <pre>$ git clone git://github.com/xto/SUTA</pre> + </p> + + <div class="footer"> + get the source code on GitHub : <a href="http://github.com/xto/SUTA">xto/SUTA</a> + </div> + + </div> + + +</body> +</html> diff --git a/src/TestSubject.php b/src/TestSubject.php index fa3ace0..16bb17e 100644 --- a/src/TestSubject.php +++ b/src/TestSubject.php @@ -1,54 +1,55 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'Expectations.php'; class TestSubject{ private $__subject; public function __construct($subject) { - $this->__subject = $subject; + $this->__subject = $subject; + } function __call($method_name, $args) { if(method_exists($this->__subject, $method_name)) { return new TestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); } else if(method_exists(Expectations, $method_name)) { array_unshift($args,$this->__subject); return call_user_func_array( array(Expectations, $method_name), $args); } else { throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); } } public function __toString() { return (string)$this->__subject; } } ?>
xto/SUTA
c7f11e1ffe2d66e560de1642ad6cdb90b0c5a03a
Made the site at least tolerable for the human eye
diff --git a/index.html b/index.html index 787bedc..5cf2733 100644 --- a/index.html +++ b/index.html @@ -1,84 +1,83 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>xto/SUTA @ GitHub</title> - <style type="text/css"> + <style type="text/css"> body { - margin-top: 1.0em; - background-color: #242dff; - font-family: "Helvetica,Arial,FreeSans"; - color: #ffffff; - } - #container { - margin: 0 auto; - width: 700px; - } - h1 { font-size: 3.8em; color: #dbd200; margin-bottom: 3px; } - h1 .small { font-size: 0.4em; } - h1 a { text-decoration: none } - h2 { font-size: 1.5em; color: #dbd200; } - h3 { text-align: center; color: #dbd200; } - a { color: #dbd200; } - .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} - .download { float: right; } + margin-top: 1.0em; + background-color: FFFFFF; + font-family: "Helvetica,Arial,FreeSans"; + + } + #container { + margin: 0 auto; + width: 700px; + } + h1 { font-size: 3.8em; color: #FFFFFF; margin-bottom: 3px; background-color:#333333;} + h1 .small { font-size: 0.4em; background-color:#333333;} + h1 a { text-decoration: none;background-color:#333333;color:#FFFFFF } + h2 { font-size: 1.5em; color: #FFFFFF;background-color:#333333 } + h3 { text-align: center; color: #FFFFFF; background-color:#333333} + .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} + .download { float: right; } pre { background: #000; color: #fff; padding: 15px;} - hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} - .footer { text-align:center; padding-top:30px; font-style: italic; } + hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} + .footer { text-align:center; padding-top:30px; font-style: italic; } </style> </head> <body> <a href="http://github.com/xto/SUTA"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> <div id="container"> <div class="download"> <a href="http://github.com/xto/SUTA/zipball/master"> <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a> <a href="http://github.com/xto/SUTA/tarball/master"> <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a> </div> <h1><a href="http://github.com/xto/SUTA">SUTA</a> - <span class="small">by <a href="http://github.com/xto">xto</a></span></h1> + <span class="small">by <a href="http://github.com/xto">Xavier To, Nicholas Lemay and Francis Falardeau</a></span></h1> <div class="description"> Simplified Unit Testing Add-on for phpunit </div> <h2>Dependencies</h2> <p>PHPUnit and Testing_Selenium</p> <h2>License</h2> <p>GPL</p> <h2>Authors</h2> <p>nicholaslemay ([email protected]) <br/>Xavier Tô ([email protected]) <br/> <br/> </p> <h2>Contact</h2> <p>Xavier Tô ([email protected]) <br/> </p> <h2>Download</h2> <p> You can download this project in either <a href="http://github.com/xto/SUTA/zipball/master">zip</a> or <a href="http://github.com/xto/SUTA/tarball/master">tar</a> formats. </p> <p>You can also clone the project with <a href="http://git-scm.com">Git</a> by running: <pre>$ git clone git://github.com/xto/SUTA</pre> </p> <div class="footer"> get the source code on GitHub : <a href="http://github.com/xto/SUTA">xto/SUTA</a> </div> </div> </body> </html>
xto/SUTA
4e76026f66d4e4100c2fdc3a650dd2ef0822a7a2
First pages commit
diff --git a/index.html b/index.html new file mode 100644 index 0000000..03f9801 --- /dev/null +++ b/index.html @@ -0,0 +1 @@ +My GitHub Page
xto/SUTA
ceb89bcb3c61074e066e3197a7a27c3d396a2479
github generated gh-pages branch
diff --git a/index.html b/index.html new file mode 100644 index 0000000..787bedc --- /dev/null +++ b/index.html @@ -0,0 +1,84 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + + <title>xto/SUTA @ GitHub</title> + + <style type="text/css"> + body { + margin-top: 1.0em; + background-color: #242dff; + font-family: "Helvetica,Arial,FreeSans"; + color: #ffffff; + } + #container { + margin: 0 auto; + width: 700px; + } + h1 { font-size: 3.8em; color: #dbd200; margin-bottom: 3px; } + h1 .small { font-size: 0.4em; } + h1 a { text-decoration: none } + h2 { font-size: 1.5em; color: #dbd200; } + h3 { text-align: center; color: #dbd200; } + a { color: #dbd200; } + .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} + .download { float: right; } + pre { background: #000; color: #fff; padding: 15px;} + hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} + .footer { text-align:center; padding-top:30px; font-style: italic; } + </style> + +</head> + +<body> + <a href="http://github.com/xto/SUTA"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> + + <div id="container"> + + <div class="download"> + <a href="http://github.com/xto/SUTA/zipball/master"> + <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a> + <a href="http://github.com/xto/SUTA/tarball/master"> + <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a> + </div> + + <h1><a href="http://github.com/xto/SUTA">SUTA</a> + <span class="small">by <a href="http://github.com/xto">xto</a></span></h1> + + <div class="description"> + Simplified Unit Testing Add-on for phpunit + </div> + + <h2>Dependencies</h2> +<p>PHPUnit and Testing_Selenium</p> +<h2>License</h2> +<p>GPL</p> +<h2>Authors</h2> +<p>nicholaslemay ([email protected]) <br/>Xavier Tô ([email protected]) <br/> <br/> </p> +<h2>Contact</h2> +<p>Xavier Tô ([email protected]) <br/> </p> + + + <h2>Download</h2> + <p> + You can download this project in either + <a href="http://github.com/xto/SUTA/zipball/master">zip</a> or + <a href="http://github.com/xto/SUTA/tarball/master">tar</a> formats. + </p> + <p>You can also clone the project with <a href="http://git-scm.com">Git</a> + by running: + <pre>$ git clone git://github.com/xto/SUTA</pre> + </p> + + <div class="footer"> + get the source code on GitHub : <a href="http://github.com/xto/SUTA">xto/SUTA</a> + </div> + + </div> + + +</body> +</html>
xto/SUTA
86cd6b0b0b43786c16d7c83091085f9bacfa7a1f
Added a bunch of selenium expectations. List is not complete and may require refactoring in a little while
diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php index 4389585..504e583 100644 --- a/expectations/ExpectationsSuite.php +++ b/expectations/ExpectationsSuite.php @@ -1,39 +1,42 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; + require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; require_once 'expectations/ExpectationsExpectations.php'; require_once 'expectations/TestSubjectExpectations.php'; + require_once 'selenium_expectations/SeleniumTestSubjectExpectations.php'; class ExpectationsSuite { public static function suite() { $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); $suite->addTestSuite('ExpectationsExpectations'); $suite->addTestSuite('TestSubjectExpectations'); + $suite->addTestSuite('SeleniumTestSubjectExpectations'); return $suite; } } ?> \ No newline at end of file diff --git a/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php b/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php new file mode 100644 index 0000000..638c413 --- /dev/null +++ b/expectations/selenium_expectations/SeleniumTestSubjectExpectations.php @@ -0,0 +1,162 @@ +<?php + + require_once 'src/selenium_helper/SeleniumTestSubject.php'; + + class SeleniumTestSubjectExpectations extends PHPUnit_Framework_TestCase + { + private static $selenium_test_subject; + + public static function setUpBeforeClass() + { + self::$selenium_test_subject = new SeleniumTestSubject("firefox","file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + } + + public static function tearDownAfterClass() + { + self::$selenium_test_subject->destroy(); + } + + public function setUp() + { + self::$selenium_test_subject->goesTo("file:///home/xto/projects/SUTA/expectations/selenium_expectations/selenium_test_page.html"); + } + + /** + * @test + */ + public function shouldSeeShouldRaiseAnExceptionIfElementIsNotThere() + { + try + { + self::$selenium_test_subject->shouldSee("id('non_existant_id')"); + self::fail("shouldSee should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function shouldSeeShouldSucceedWhenElementIsFound() + { + self::$selenium_test_subject->shouldSee("//*[id('test_span')]"); + } + + /** + * @test + */ + public function withTextShouldRaiseAnExceptionIfTextDoesNotMatchParameter() + { + try + { + self::$selenium_test_subject->shouldSee("//span[@id('test_span')]")->withText("Text that isn't there"); + self::fail("withText should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function withTextShouldSucceedIfTextMatchesParameter() + { + self::$selenium_test_subject->shouldSee("//span[id('test_span')]")->withText("Text"); + } + + /** + * @test + */ + public function checkedShouldRaiseAnExceptionIfElementIsNotACheckboxOrARadioButton() + { + try + { + self::$selenium_test_subject->shouldSee("//span[id('test_span')]")->checked(); + self::fail("checked should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function checkedShouldSucceedIfElementIsACheckboxThatIsChecked() + { + self::$selenium_test_subject->clicks("//input[@name='test_checkbox']"); + self::$selenium_test_subject->shouldSee("//input[@name='test_checkbox']")->checked(); + + } + + /** + * @test + */ + public function checkedShouldSucceedIfElementIsARadiobuttonThatIsChecked() + { + self::$selenium_test_subject->clicks("//input[@name='test_radio']"); + self::$selenium_test_subject->shouldSee("//input[@name='test_radio']")->checked(); + + } + + /** + * @test + */ + public function checkedShouldFailIfElementIsAnUncheckedCheckbox() + { + try + { + self::$selenium_test_subject->shouldSee("//input[@name='test_checkbox']")->checked(); + self::fail("checked should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function checkedShouldFailIfElementIsAnUncheckedRadiobutton() + { + try + { + self::$selenium_test_subject->shouldSee("//input[@name='test_radio']")->checked(); + self::fail("checked should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function selectedFailWhenOptionDoesNotExist() + { + try + { + self::$selenium_test_subject->selects("Unknown Option")->from("test_select"); + self::$selenium_test_subject->shouldSee("//select/option[2]")->selected(); + self::fail("selected should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function selectedFailWhenOptionIsNotSelected() + { + try + { + self::$selenium_test_subject->selects("Option")->from("test_select"); + self::$selenium_test_subject->shouldSee("//select/option[1]")->selected(); + self::fail("selected should have failed"); + } + catch(Exception $e){} + } + + /** + * @test + */ + public function selectedShouldSucceedWhenOptionIsSelected() + { + self::$selenium_test_subject->selects("Option 2")->from("test_select"); + self::$selenium_test_subject->shouldSee("//select/option[2]")->selected(); + } + } +?> \ No newline at end of file diff --git a/expectations/selenium_expectations/selenium_test_page.html b/expectations/selenium_expectations/selenium_test_page.html new file mode 100644 index 0000000..c27f30c --- /dev/null +++ b/expectations/selenium_expectations/selenium_test_page.html @@ -0,0 +1,22 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> +<html> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +<title>Insert title here</title> +</head> +<body> +<span id="test_span">Text</span> +<br /> +<label for='test_checkbox'>Checkbox</label><input name="test_checkbox" type="checkbox"/> +<br /> +<label for='test_radio'>Radio</label><input name="test_radio" type="radio"/> +<br /> + +<label for=test_select">Select</label> +<select id="test_select"> + <option>Option 1</option> + <option>Option 2</option> + <option>Option 3</option> +</select> +</body> +</html> \ No newline at end of file diff --git a/src/SeleniumTestSubject.php b/src/selenium_helper/SeleniumTestSubject.php similarity index 56% rename from src/SeleniumTestSubject.php rename to src/selenium_helper/SeleniumTestSubject.php index ef45584..b6b8117 100644 --- a/src/SeleniumTestSubject.php +++ b/src/selenium_helper/SeleniumTestSubject.php @@ -1,84 +1,125 @@ <?php require_once 'Testing/Selenium.php'; - require_once 'Expectations.php'; + require_once dirname(__FILE__).'/../Expectations.php'; class SeleniumTestSubject { private $selenium; private $lastKnownLocator; + public function __construct($browser,$website) { $this->selenium = new Testing_Selenium($browser,$website); $this->selenium->start(); return $this; } + public function destroy() + { + $this->selenium->close(); + $this->selenium->stop(); + } + /** + * Actions + */ public function goesTo($url) { $this->selenium->open($url); return $this; } public function fillsOut($text_field_locator) { $this->lastKnownLocator = $text_field_locator; return $this; } public function with($value) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to type... Please specify where to type."); $this->selenium->type($this->lastKnownLocator,$value); $this->lastKnownLocator = null; return $this; } public function clicks($locator) { $this->selenium->click($locator); return $this; } public function and_then() { return $this; } public function waitsForPageToLoad() { $this->selenium->waitForPageToLoad(30000); } public function drags($objects_locator) { $this->lastKnownLocator = $locator; return $this; } public function dropsOn($destinations_locator) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to drop... Please specify where to drop the object."); $this->selenium->dragAndDropToObject($this->lastKnownLocator,$destinations_locator); return $this; } public function checks($checkbox_or_radio_button_locator) { return $this->clicks($checkbox_or_radio_button_locator); } public function selects($value) { $this->lastKnownLocator = $value; return $this; } public function from($dropdown_list_locator) { Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to pick from... Please specify where to find the selection."); - $this->selenium->select($dropdown_list_locator,$this->lastKnownLocator); + $this->selenium->select($dropdown_list_locator,'label='.$this->lastKnownLocator); + $this->lastKnownLocator = null; + } + + + /** + * Expectations + */ + public function shouldSee($element_locator, $message = "Element was not found! Verify that the locator is correct!" ){ + Expectations::shouldBeTrue($this->selenium->isElementPresent($element_locator),$message ); + $this->lastKnownLocator = $element_locator; + return $this; + } + + public function withText($expected_text) + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); + Expectations::shouldEqual($this->selenium->getText($this->lastKnownLocator), $expected_text); + $this->lastKnownLocator = null; } + public function checked() + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"No element was specified. Did you forget the call to shouldSee ?"); + Expectations::shouldBeTrue($this->selenium->isChecked($this->lastKnownLocator)); + $this->lastKnownLocator = null; + } + + public function selected() + { + Expectations::shouldEqual($this->selenium->getValue($this->lastKnownLocator), $this->selenium->getSelectedLabel($this->lastKnownLocator."/..")); + $this->lastKnownLocator = null; + } + + } ?> \ No newline at end of file
xto/SUTA
2e52c9bab30af2e2df1daa4d3a3c6c70ccde92cd
Added basic functionality for selenium
diff --git a/README b/README index 2bd033e..0cb62d5 100644 --- a/README +++ b/README @@ -1,30 +1,30 @@ This is just a preliminary commit of an idea for a DSL for PHPUnit. We needed something simple to write some tests and couldn't find anything to suit our needs. What we're trying to achieve is a simple syntax for unit test and eventually driving Selenium to do UI testing. The syntax will be something like $bob = new User(); $bob->logs_in()->and()->fills_out(Field::username)->with("bob")-> and()->fills_out(Field::password)->with("qwerty")-> and()->clicks(Button::login)->and()->shouldBeLoggedin(); This type of syntax should hopefully help people who aren't developers understand and write some tests. -As fare as UnitTesting is concerned, we are trying to approach it with the BDD philosophy. +As far as UnitTesting is concerned, we are trying to approach it with the BDD philosophy. Using this PHPUnit ADD-ON, the testing syntax for expectations would now look like this $nicholas = new TestSubject(new DummyUser("Nicholas",true)); $nicholas->getName()->shouldEqual("Nicholas"); instead of : $nicholas = new DummyUser("Nicholas",true); $this->assertEquals( $nicholas->getName(),"Nicholas"); More to come ! diff --git a/src/SeleniumTestSubject.php b/src/SeleniumTestSubject.php index f9f8c81..ef45584 100644 --- a/src/SeleniumTestSubject.php +++ b/src/SeleniumTestSubject.php @@ -1,47 +1,84 @@ <?php require_once 'Testing/Selenium.php'; - + require_once 'Expectations.php'; class SeleniumTestSubject { private $selenium; private $lastKnownLocator; public function __construct($browser,$website) { $this->selenium = new Testing_Selenium($browser,$website); $this->selenium->start(); - $this->selenium->open($website); return $this; } - public function fillsOut($locator) + public function goesTo($url) { - $this->lastKnownLocator = $locator; + $this->selenium->open($url); + return $this; + } + + public function fillsOut($text_field_locator) + { + $this->lastKnownLocator = $text_field_locator; return $this; } public function with($value) { + Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to type... Please specify where to type."); $this->selenium->type($this->lastKnownLocator,$value); + $this->lastKnownLocator = null; return $this; } public function clicks($locator) { $this->selenium->click($locator); return $this; } public function and_then() { return $this; } public function waitsForPageToLoad() { $this->selenium->waitForPageToLoad(30000); } + public function drags($objects_locator) + { + $this->lastKnownLocator = $locator; + return $this; + } + + public function dropsOn($destinations_locator) + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to drop... Please specify where to drop the object."); + $this->selenium->dragAndDropToObject($this->lastKnownLocator,$destinations_locator); + return $this; + } + + public function checks($checkbox_or_radio_button_locator) + { + return $this->clicks($checkbox_or_radio_button_locator); + } + + public function selects($value) + { + $this->lastKnownLocator = $value; + return $this; + } + + public function from($dropdown_list_locator) + { + Expectations::shouldNotBeNull($this->lastKnownLocator,"Nowhere to pick from... Please specify where to find the selection."); + $this->selenium->select($dropdown_list_locator,$this->lastKnownLocator); + } + } ?> \ No newline at end of file
xto/SUTA
cb15db8759d4239d9ad3874c05c8c4c6975e33e5
Added a .gitingore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8d4bfcf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +nohup.out diff --git a/nohup.out b/nohup.out deleted file mode 100644 index e69de29..0000000
xto/SUTA
1d08d7db662bf202b0568af23534b55283f91148
Updating readme wih text for BDD aspect of add-on
diff --git a/README b/README index 6c3e9fe..9bb5490 100644 --- a/README +++ b/README @@ -1,18 +1,30 @@ This is just a preliminary commit of an idea for a DSL for PHPUnit. We needed siomething simple to write some tests and couldn't find anything to suit our needs. What we're trying to achieve is a simple syntax for unit test and eventually driving Selenium to do UI testing. The syntax will be something like $bob = new User(); $bob->logs_in()->and()->fills_out(Field::username)->with("bob")-> and()->fills_out(Field::password)->with("qwerty")-> and()->clicks(Button::login)->and()->shouldBeLoggedin(); This type of syntax should hopefully help people who aren't developers understand and write some tests. + +As fare as UnitTesting is concerned, we are trying to approach it with the BDD philosophy. +Using this PHPUnit ADD-ON, the testing syntax for expectations would now look like this + +$nicholas = new TestSubject(new DummyUser("Nicholas",true)); +$nicholas->getName()->shouldEqual("Nicholas"); + +instead of : + +$nicholas = new DummyUser("Nicholas",true); +$this->assertEquals( $nicholas->getName(),"Nicholas"); + More to come !
xto/SUTA
14249540108ab0af271a5f51f4a9bdb12a3ce662
Added basic selenium helper object
diff --git a/.buildpath b/.buildpath index 09d953e..f68a211 100644 --- a/.buildpath +++ b/.buildpath @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <buildpath> <buildpathentry kind="src" path=""/> <buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/> - <buildpathentry external="true" kind="lib" path="/usr/share/php/PHPUnit"/> + <buildpathentry external="true" kind="lib" path="/usr/share/php"/> </buildpath> diff --git a/.settings/org.eclipse.php.core.prefs b/.settings/org.eclipse.php.core.prefs index c1c87e4..9f96b95 100644 --- a/.settings/org.eclipse.php.core.prefs +++ b/.settings/org.eclipse.php.core.prefs @@ -1,3 +1,3 @@ -#Mon Feb 01 20:43:29 EST 2010 +#Sat Feb 06 08:19:53 EST 2010 eclipse.preferences.version=1 -include_path=0;/SUTA\u00051;/usr/share/php/PHPUnit +include_path=0;/SUTA\u00051;/usr/share/php diff --git a/src/SeleniumTestSubject.php b/src/SeleniumTestSubject.php new file mode 100644 index 0000000..f9f8c81 --- /dev/null +++ b/src/SeleniumTestSubject.php @@ -0,0 +1,47 @@ +<?php + require_once 'Testing/Selenium.php'; + + class SeleniumTestSubject + { + + private $selenium; + private $lastKnownLocator; + + public function __construct($browser,$website) + { + $this->selenium = new Testing_Selenium($browser,$website); + $this->selenium->start(); + $this->selenium->open($website); + return $this; + } + + public function fillsOut($locator) + { + $this->lastKnownLocator = $locator; + return $this; + } + + public function with($value) + { + $this->selenium->type($this->lastKnownLocator,$value); + return $this; + } + + public function clicks($locator) + { + $this->selenium->click($locator); + return $this; + } + + public function and_then() + { + return $this; + } + + public function waitsForPageToLoad() + { + $this->selenium->waitForPageToLoad(30000); + } + + } +?> \ No newline at end of file
xto/SUTA
9068d6482af710ebf86792515f89f893381ec582
Added some meat to the README
diff --git a/README b/README index 0dab30d..6c3e9fe 100644 --- a/README +++ b/README @@ -1,3 +1,18 @@ -This is just a preliminary commit of an idea for a DSL for PHPUnit. We needed siomething simple to write some tests and couldn't find anything to suit our needs. +This is just a preliminary commit of an idea for a DSL for PHPUnit. + +We needed siomething simple to write some tests and couldn't find anything to suit our needs. + +What we're trying to achieve is a simple syntax for unit test and eventually driving Selenium to do UI testing. + +The syntax will be something like + +$bob = new User(); + +$bob->logs_in()->and()->fills_out(Field::username)->with("bob")-> +and()->fills_out(Field::password)->with("qwerty")-> +and()->clicks(Button::login)->and()->shouldBeLoggedin(); + +This type of syntax should hopefully help people who aren't developers understand and write some tests. + +More to come ! -We'll try to update this as we go along. For now, use at your own risk.
xto/SUTA
c082dbe3abae6a3a039033c84e330869c2768880
Added a few asserts for null and not null
diff --git a/.externalToolBuilders/PHPUNIT-AUTOTEST.launch b/.externalToolBuilders/PHPUNIT-AUTOTEST.launch index 34a3323..efffb4d 100644 --- a/.externalToolBuilders/PHPUNIT-AUTOTEST.launch +++ b/.externalToolBuilders/PHPUNIT-AUTOTEST.launch @@ -1,9 +1,9 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType"> <booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="/usr/bin/php"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/> -<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="/usr/bin/phpunit --include-path &quot;${project_loc}&quot; ${project_loc}/expectations/ExpectationsSuite.php"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="/usr/bin/phpunit --include-path &quot;${project_loc}&quot; ${project_loc}/expectations/ExpectationsSuite.php"/> <booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc}"/> </launchConfiguration> diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php index 0c85062..32a6f03 100644 --- a/expectations/ExpectationsExpectations.php +++ b/expectations/ExpectationsExpectations.php @@ -1,120 +1,140 @@ <?php require_once 'src/Expectations.php'; class ExpectationsExpectations extends PHPUnit_Framework_TestCase { /** * @test */ public function ShouldBeTrueShouldBehaveJustLikeassertTrue() { Expectations::shouldBeTrue(true); self::assertTrue(true); try { self::assertTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeFalseShouldBehaveJustLikeassertFalse() { Expectations::shouldBeFalse(false); self::assertFalse(false); try { self::assertFalse(True); throw new Exception("assertFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeFalse(true); throw new Exception("shouldBeFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldEqualShouldBehaveLikeAsserEqual() { self::assertEquals("tom","tom"); Expectations::shouldEqual("tom","tom"); try { self::assertEquals("foo", "bar"); throw new Exception("assertEquals should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldEqual("foo", "bar"); throw new Exception("shouldEqual should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } public function ShouldBeNullShouldBehaveLikeAssertNull() { Expectations::shouldBeNull(null); + self::assertNull(null); + try { self::assertNull("Something that isn't null"); throw new Exception("assertNull should fail if something not null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } + + try { + Expectations::shouldBeNull("Something that isn't null"); + throw new Exception("shouldBeNull should fail if something not null"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } } public function ShouldNotBeNullShouldBehaveLikeAssertNotNull() { - self::assertNull("Something not null"); - Expectations::shouldBeNull("Something not null"); + self::assertNotNull("Something not null"); + Expectations::shouldNotBeNull("Something not null"); + try { - + self::assertNotNull(null); + throw new Exception("assertNotNull should fail if something null"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try { + Expectations::shouldNotNull(null); + throw new Exception("shoulNotdBeNull should fail if something null"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } } ?> \ No newline at end of file diff --git a/nohup.out b/nohup.out new file mode 100644 index 0000000..e69de29 diff --git a/src/Expectations.php b/src/Expectations.php index 230d4dc..2e8631e 100644 --- a/src/Expectations.php +++ b/src/Expectations.php @@ -1,42 +1,52 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'PHPUnit/Framework.php'; class Expectations extends PHPUnit_Framework_Assert { public static function shouldBeTrue($value, $message="") { self::assertThat($value, self::isTrue(), $message); } public static function shouldBeFalse($value, $message="") { self::assertThat($value, self::isFalse(), $message); } public static function shouldEqual($actual, $expected, $message = '') { self::assertEquals($expected, $actual, $message); } + + public static function shouldBeNull($value, $message = '') + { + self::assertNull($value, $message); + } + + public static function shouldNotBeNull($value, $message = '') + { + self::assertNotNull($value, $message); + } } ?>
xto/SUTA
a9d8c5e35c9245132f19033974b824067eb7e77d
added partial expectations for null and not null
diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php index 6fe7883..0c85062 100644 --- a/expectations/ExpectationsExpectations.php +++ b/expectations/ExpectationsExpectations.php @@ -1,97 +1,120 @@ <?php require_once 'src/Expectations.php'; class ExpectationsExpectations extends PHPUnit_Framework_TestCase { /** * @test */ public function ShouldBeTrueShouldBehaveJustLikeassertTrue() { Expectations::shouldBeTrue(true); self::assertTrue(true); try { self::assertTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeTrue(false); throw new Exception("assertTrue should fail with false"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldBeFalseShouldBehaveJustLikeassertFalse() { Expectations::shouldBeFalse(false); self::assertFalse(false); try { self::assertFalse(True); throw new Exception("assertFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldBeFalse(true); throw new Exception("shouldBeFalse should fail with true"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } /** * @test */ public function ShouldEqualShouldBehaveLikeAsserEqual() { self::assertEquals("tom","tom"); Expectations::shouldEqual("tom","tom"); try { self::assertEquals("foo", "bar"); throw new Exception("assertEquals should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } try { Expectations::shouldEqual("foo", "bar"); throw new Exception("shouldEqual should fail with foo and bar"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } } + + public function ShouldBeNullShouldBehaveLikeAssertNull() + { + Expectations::shouldBeNull(null); + try { + self::assertNull("Something that isn't null"); + throw new Exception("assertNull should fail if something not null"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + } + public function ShouldNotBeNullShouldBehaveLikeAssertNotNull() + { + self::assertNull("Something not null"); + Expectations::shouldBeNull("Something not null"); + try { + + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + } } ?> \ No newline at end of file
xto/SUTA
0759fac649c73818376807c5660a51baa5e939cf
Removed user specific autotest configuration
diff --git a/.externalToolBuilders/PHPUNIT-AUTOTEST.launch b/.externalToolBuilders/PHPUNIT-AUTOTEST.launch index f80e933..34a3323 100644 --- a/.externalToolBuilders/PHPUNIT-AUTOTEST.launch +++ b/.externalToolBuilders/PHPUNIT-AUTOTEST.launch @@ -1,9 +1,9 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType"> <booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="/usr/bin/php"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/> -<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="/usr/bin/phpunit --include-path &quot;${project_loc}&quot; /home/nick/workspacePHP/SUTA/expectations/ExpectationsSuite.php"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="/usr/bin/phpunit --include-path &quot;${project_loc}&quot; ${project_loc}/expectations/ExpectationsSuite.php"/> <booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc}"/> </launchConfiguration>
xto/SUTA
060e4c97bf23b53502b873b54ca1142aba7dbb33
Refactored test method names
diff --git a/expectations/TestSubjectExpectations.php b/expectations/TestSubjectExpectations.php index f7686ca..28b8e92 100644 --- a/expectations/TestSubjectExpectations.php +++ b/expectations/TestSubjectExpectations.php @@ -1,65 +1,63 @@ <?php /* Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'src/TestSubject.php'; require_once 'DummyUser.php'; class TestSubjectExpectations extends PHPUnit_Framework_TestCase { /** * @test */ - public function TestSubjectShouldSupportShouldBeTrueExpectation() + public function TestSubjectShouldHaveMethod_shouldBeTrue() { $nicholas = new TestSubject(new DummyUser("Nicholas",true)); - $nicholas->isRegistered()->shouldBeTrue(); + $nicholas->isRegistered()->shouldBeTrue(); } /** * @test */ - public function TestSubjectShouldSupportShouldBeFalseExpectation() + public function TestSubjectShouldHaveMethod_shouldBeFalse() { $nicholas = new TestSubject(new DummyUser("Nicholas",false)); $nicholas->isRegistered()->shouldBeFalse(); } /** * @test */ - public function TestSubjectShouldSupportShouldEqualExpectation() + public function TestSubjectShouldHaveMethod_shouldEqual() { $nicholas = new TestSubject(new DummyUser("Nicholas",true)); $nicholas->getName()->shouldEqual("Nicholas"); } /** * @test */ public function TestSubjectShouldSupportToStringInOrderToSupportDebug() { $nicholas = new TestSubject(new DummyUser("Nicholas",true)); self::assertEquals($nicholas->__toString(), "Nicholas"); } - - } ?>
xto/SUTA
b262bdca7450789a22878c889961ee125d7db91c
Refactoring project stucture to have a test project.
diff --git a/.buildpath b/.buildpath new file mode 100644 index 0000000..09d953e --- /dev/null +++ b/.buildpath @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<buildpath> + <buildpathentry kind="src" path=""/> + <buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/> + <buildpathentry external="true" kind="lib" path="/usr/share/php/PHPUnit"/> +</buildpath> diff --git a/.externalToolBuilders/PHPUNIT-AUTOTEST.launch b/.externalToolBuilders/PHPUNIT-AUTOTEST.launch new file mode 100644 index 0000000..f80e933 --- /dev/null +++ b/.externalToolBuilders/PHPUNIT-AUTOTEST.launch @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType"> +<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="/usr/bin/php"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="/usr/bin/phpunit --include-path &quot;${project_loc}&quot; /home/nick/workspacePHP/SUTA/expectations/ExpectationsSuite.php"/> +<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc}"/> +</launchConfiguration> diff --git a/.project b/.project new file mode 100644 index 0000000..cb9ab3a --- /dev/null +++ b/.project @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>SUTA</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.wst.validation.validationbuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.dltk.core.scriptbuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.ui.externaltools.ExternalToolBuilder</name> + <triggers>auto,full,incremental,</triggers> + <arguments> + <dictionary> + <key>LaunchConfigHandle</key> + <value>&lt;project&gt;/.externalToolBuilders/PHPUNIT-AUTOTEST.launch</value> + </dictionary> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.php.core.PHPNature</nature> + </natures> +</projectDescription> diff --git a/.settings/org.eclipse.php.core.prefs b/.settings/org.eclipse.php.core.prefs new file mode 100644 index 0000000..c1c87e4 --- /dev/null +++ b/.settings/org.eclipse.php.core.prefs @@ -0,0 +1,3 @@ +#Mon Feb 01 20:43:29 EST 2010 +eclipse.preferences.version=1 +include_path=0;/SUTA\u00051;/usr/share/php/PHPUnit diff --git a/expectations/DummyUser.php b/expectations/DummyUser.php new file mode 100644 index 0000000..4142f86 --- /dev/null +++ b/expectations/DummyUser.php @@ -0,0 +1,49 @@ + + +<?php + /* + Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + + */ + + class DummyUser + { + private $__name; + private $__registered; + + public function __construct($name,$registered) + { + $this->__name = $name; + $this->__registered = $registered; + } + + public function getName() + { + return $this->__name; + } + + public function isRegistered() + { + return $this->__registered; + } + + public function __toString() + { + return $this->__name; + } + } + +?> \ No newline at end of file diff --git a/expectations/ExpectationsExpectations.php b/expectations/ExpectationsExpectations.php new file mode 100644 index 0000000..6fe7883 --- /dev/null +++ b/expectations/ExpectationsExpectations.php @@ -0,0 +1,97 @@ +<?php + + require_once 'src/Expectations.php'; + + class ExpectationsExpectations extends PHPUnit_Framework_TestCase + { + + /** + * @test + */ + public function ShouldBeTrueShouldBehaveJustLikeassertTrue() + { + Expectations::shouldBeTrue(true); + self::assertTrue(true); + + try + { + self::assertTrue(false); + throw new Exception("assertTrue should fail with false"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try + { + Expectations::shouldBeTrue(false); + throw new Exception("assertTrue should fail with false"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + + } + + /** + * @test + */ + public function ShouldBeFalseShouldBehaveJustLikeassertFalse() + { + Expectations::shouldBeFalse(false); + self::assertFalse(false); + + try + { + self::assertFalse(True); + throw new Exception("assertFalse should fail with true"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try + { + Expectations::shouldBeFalse(true); + throw new Exception("shouldBeFalse should fail with true"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + } + + + /** + * @test + */ + public function ShouldEqualShouldBehaveLikeAsserEqual() + { + self::assertEquals("tom","tom"); + Expectations::shouldEqual("tom","tom"); + + try + { + self::assertEquals("foo", "bar"); + throw new Exception("assertEquals should fail with foo and bar"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + try + { + Expectations::shouldEqual("foo", "bar"); + throw new Exception("shouldEqual should fail with foo and bar"); + } + catch (PHPUnit_Framework_ExpectationFailedException $e) + { + } + + } + + } + + +?> \ No newline at end of file diff --git a/expectations/ExpectationsSuite.php b/expectations/ExpectationsSuite.php new file mode 100644 index 0000000..4389585 --- /dev/null +++ b/expectations/ExpectationsSuite.php @@ -0,0 +1,39 @@ + +<?php + /* + Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + + */ + + require_once 'PHPUnit/Framework.php'; + require_once 'expectations/ExpectationsExpectations.php'; + require_once 'expectations/TestSubjectExpectations.php'; + + class ExpectationsSuite + { + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('Project SUTA'); + + $suite->addTestSuite('ExpectationsExpectations'); + $suite->addTestSuite('TestSubjectExpectations'); + + return $suite; + } + } + + +?> \ No newline at end of file diff --git a/expectations/TestSubjectExpectations.php b/expectations/TestSubjectExpectations.php new file mode 100644 index 0000000..f7686ca --- /dev/null +++ b/expectations/TestSubjectExpectations.php @@ -0,0 +1,65 @@ +<?php +/* + Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +*/ + + require_once 'src/TestSubject.php'; + require_once 'DummyUser.php'; + + class TestSubjectExpectations extends PHPUnit_Framework_TestCase + { + /** + * @test + */ + public function TestSubjectShouldSupportShouldBeTrueExpectation() + { + $nicholas = new TestSubject(new DummyUser("Nicholas",true)); + $nicholas->isRegistered()->shouldBeTrue(); + } + + /** + * @test + */ + public function TestSubjectShouldSupportShouldBeFalseExpectation() + { + $nicholas = new TestSubject(new DummyUser("Nicholas",false)); + $nicholas->isRegistered()->shouldBeFalse(); + } + + /** + * @test + */ + public function TestSubjectShouldSupportShouldEqualExpectation() + { + $nicholas = new TestSubject(new DummyUser("Nicholas",true)); + $nicholas->getName()->shouldEqual("Nicholas"); + } + + /** + * @test + */ + public function TestSubjectShouldSupportToStringInOrderToSupportDebug() + { + $nicholas = new TestSubject(new DummyUser("Nicholas",true)); + self::assertEquals($nicholas->__toString(), "Nicholas"); + } + + + + } + +?> diff --git a/src/Expectations.php b/src/Expectations.php new file mode 100644 index 0000000..230d4dc --- /dev/null +++ b/src/Expectations.php @@ -0,0 +1,42 @@ +<?php + /* + Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + + */ + + require_once 'PHPUnit/Framework.php'; + + class Expectations extends PHPUnit_Framework_Assert + { + public static function shouldBeTrue($value, $message="") + { + self::assertThat($value, self::isTrue(), $message); + } + + public static function shouldBeFalse($value, $message="") + { + self::assertThat($value, self::isFalse(), $message); + } + + public static function shouldEqual($actual, $expected, $message = '') + { + self::assertEquals($expected, $actual, $message); + } + } + + + +?> diff --git a/src/TestSubject.php b/src/TestSubject.php new file mode 100644 index 0000000..fa3ace0 --- /dev/null +++ b/src/TestSubject.php @@ -0,0 +1,54 @@ +<?php +/* + Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +*/ + require_once 'Expectations.php'; + + class TestSubject{ + + private $__subject; + + public function __construct($subject) + { + $this->__subject = $subject; + } + + function __call($method_name, $args) + { + if(method_exists($this->__subject, $method_name)) + { + return new TestSubject(call_user_func_array( array($this->__subject, $method_name), $args)); + } + else if(method_exists(Expectations, $method_name)) + { + array_unshift($args,$this->__subject); + return call_user_func_array( array(Expectations, $method_name), $args); + } + else + { + throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__subject)." instance."); + } + } + + public function __toString() + { + return (string)$this->__subject; + } + + } + +?>
xto/SUTA
e834dfa5f1ef0d5f56d22fae5633a569a85a6af1
Added licensing disclaimer and gpl copy
diff --git a/BDDAsserts.php b/BDDAsserts.php index 6a0c579..130f9d5 100644 --- a/BDDAsserts.php +++ b/BDDAsserts.php @@ -1,26 +1,42 @@ <?php +/* + Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +*/ require_once 'PHPUnit/Framework.php'; class BDDAsserts extends PHPUnit_Framework_Assert { public static function shouldBeTrue($value, $message="") { self::assertThat($value, self::isTrue(), $message); } public static function shouldBeFalse($value, $message="") { self::assertThat($value, self::isFalse(), $message); } public static function shouldEqual($actual, $expected, $message = '') { self::assertEquals($expected, $actual, $message); } } ?> diff --git a/MesTests.php b/MesTests.php index b2b0419..5a069f2 100644 --- a/MesTests.php +++ b/MesTests.php @@ -1,38 +1,54 @@ <?php - +/* + Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +*/ require_once 'TestObject.php'; class MesTests extends PHPUnit_Framework_TestCase { /** * @test */ public function UsersRegistrationShouldBeSetProperlyWhenSetToTrue() { $nicholas = new TestObject(new User("Nicholas",true)); $nicholas->isRegistered()->shouldBeTrue(); } /** * @test * Test that fails on purpose */ public function UsersRegistrationShouldBeSetProperlyWhenSetToFalse() { $nicholas = new TestObject(new User("Nicholas",true)); $nicholas->isRegistered()->shouldBeFalse("Wow I Miss my python syntax"); } /** * @test * */ public function UsersNameShouldBeSetProperly() { $nicholas = new TestObject(new User("Nicholas",true)); $nicholas->getName()->shouldEqual("Nicholas"); } } ?> diff --git a/TestObject.php b/TestObject.php index c593806..dd11f87 100644 --- a/TestObject.php +++ b/TestObject.php @@ -1,62 +1,78 @@ <?php - +/* + Copyright 2010 Nicholas Lemay, Xavier Tô, Francis Falardeau + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +*/ require_once 'BDDAsserts.php'; class User { private $__name; private $__registered; public function __construct($name,$registered) { $this->__name = $name; $this->__registered = $registered; } public function getName() { return $this->__name; } public function isRegistered() { return $this->__registered; } } class TestObject{ private $__objectToTest; public function __construct($objectToTest) { $this->__objectToTest = $objectToTest; } function __call($method_name, $args) { if(method_exists($this->__objectToTest, $method_name)) { return new TestObject(call_user_func_array( array($this->__objectToTest,$method_name), $args)); } else if(method_exists(BDDAsserts, $method_name)) { array_unshift($args,$this->__objectToTest); return call_user_func_array( array(BDDAsserts,$method_name), $args); } else { throw new Exception('Unknown method '.$method_name."called on ".get_class($this->__objectToTest)." instance."); } } public function __toString() { return (string)$this->__objectToTest; } } ?> diff --git a/gpl.txt b/gpl.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/gpl.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>.
smtlaissezfaire/hopcroft
593c932c5785464a7ae66fe047d236a567d32172
Fix a comment
diff --git a/lib/hopcroft/regex/regex_parser.treetop b/lib/hopcroft/regex/regex_parser.treetop index dcd2667..10c4435 100644 --- a/lib/hopcroft/regex/regex_parser.treetop +++ b/lib/hopcroft/regex/regex_parser.treetop @@ -1,168 +1,168 @@ # # This grammar is taken from GNU's grep grammar, with slight modifications. It doesn't # support backreferencing, metachars, negated character classes, repetion # with {n,m}, etc. - although there is no reason that it couldn't. # -# In addition, GNU's grep grammar is modified for an LL parser. LL parsers can't +# In addition, the GNU grep grammar is modified for an LL parser. LL parsers can't # process left recursion without under going left factorization: # # See: # http://treetop.rubyforge.org/pitfalls_and_advanced_techniques.html # http://en.wikipedia.org/wiki/Left_recursion#Removing_immediate_left_recursion # # # From GNU grep: # The grammar understood by the parser is as follows. # # regexp: # regexp OR branch # branch # # branch: # branch closure # closure # # closure: # closure QMARK # closure STAR # closure PLUS # closure REPMN # atom # # atom: # <normal character> # <multibyte character> # ANYCHAR # MBCSET # CSET # BACKREF # BEGLINE # ENDLINE # BEGWORD # ENDWORD # LIMWORD # NOTLIMWORD # CRANGE # LPAREN regexp RPAREN # <empty> # # The parser builds a parse tree in postfix form in an array of tokens. module Hopcroft module Regex grammar TreetopRegex rule regex branch regex_prime <SyntaxNodes::Regex> end rule regex_prime OR branch subexpression:regex_prime <SyntaxNodes::Alternation> / epsilon end rule branch closure branch_prime <SyntaxNodes::Branch> end rule branch_prime closure branch_prime <SyntaxNodes::Concatenation> / epsilon end rule epsilon "" <SyntaxNodes::Epsilon> end rule closure atom closure_prime <SyntaxNodes::Closure> end rule closure_prime kleen_star / one_or_more_expr / optional_expr / epsilon end rule kleen_star "*" <SyntaxNodes::KleenStar> end rule one_or_more_expr "+" <SyntaxNodes::OneOrMoreExpression> end rule optional_expr "?" <SyntaxNodes::OptionalExpression> end rule atom parenthesized_expression / dot / character_class / single_char end rule dot "." <SyntaxNodes::Dot> end rule parenthesized_expression LEFT_PARENS regex RIGHT_PARENS <SyntaxNodes::ParenthesizedExpression> end rule character_class LEFT_BRACKET inner_char_class RIGHT_BRACKET <SyntaxNodes::CharacterClass> end rule inner_char_class inner_char_class_expr+ <SyntaxNodes::MultipleInnerCharClass> end rule inner_char_class_expr one:single_char "-" two:single_char <SyntaxNodes::TwoCharClass> / single_char <SyntaxNodes::OneCharClass> end rule single_char non_special_char / escaped_char end rule non_special_char !("(" / ")" / "[" / "+" / "?" / "+" / "]" / "|" / "*" / "\\") any_char:ANY_CHAR <SyntaxNodes::Char> end rule escaped_char ESCAPE any_char:ANY_CHAR <SyntaxNodes::Char> end rule OR "|" end rule ANY_CHAR . end rule LEFT_BRACKET "[" end rule RIGHT_BRACKET "]" end rule ESCAPE "\\" end rule LEFT_PARENS "(" end rule RIGHT_PARENS ")" end end end end
smtlaissezfaire/hopcroft
a25e4fcee379aa72886cce2eb051d72baac19d7b
Whitespace cleanup
diff --git a/README.rdoc b/README.rdoc index 7bdc75e..3b13f22 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,35 +1,35 @@ = Hopcroft A library for dealing with regular languages: Regexes and State Machines. == Example If you can understand the following, welcome to the club! ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b") - => #<Hopcroft::Regex::Alternation:0x122698c @expressions=[#<Hopcroft::Regex::Char:0x12240ec @expression="a">, #<Hopcroft::Regex::Char:0x1224a4c @expression="b">]> + => #<Hopcroft::Regex::Alternation:0x122698c @expressions=[#<Hopcroft::Regex::Char:0x12240ec @expression="a">, #<Hopcroft::Regex::Char:0x1224a4c @expression="b">]> ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine - => #<Hopcroft::Machine::StateMachine:0x121f074 @start_state=State 1 {start: true, final: false, transitions: 2}> + => #<Hopcroft::Machine::StateMachine:0x121f074 @start_state=State 1 {start: true, final: false, transitions: 2}> ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine.to_dfa - => #<Hopcroft::Machine::StateMachine:0x120d630 @start_state=State 12 {start: true, final: false, transitions: 2}> - + => #<Hopcroft::Machine::StateMachine:0x120d630 @start_state=State 12 {start: true, final: false, transitions: 2}> + ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine - => #<Hopcroft::Machine::StateMachine:0x5f1b1c @start_state=State 24 {start: true, final: false, transitions: 2}> + => #<Hopcroft::Machine::StateMachine:0x5f1b1c @start_state=State 24 {start: true, final: false, transitions: 2}> ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine.state_table - => + => +-------------+------------+------------+--------------------------------------+ | | b | a | Hopcroft::Machine::EpsilonTransition | +-------------+------------+------------+--------------------------------------+ | State 32 | * State 33 | | | | State 30 | | * State 31 | | | -> State 29 | | | State 30, State 32 | +-------------+------------+------------+--------------------------------------+ ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine.to_dfa.state_table - => + => +-------------+----------+----------+ | | a | b | +-------------+----------+----------+ | -> State 21 | State 22 | State 23 | +-------------+----------+----------+ - + diff --git a/Rakefile b/Rakefile index 6e7d314..eb79d4c 100644 --- a/Rakefile +++ b/Rakefile @@ -1,6 +1,6 @@ Dir.glob(File.dirname(__FILE__) + "/tasks/**/**").each do |file| load file end -task :default => :spec \ No newline at end of file +task :default => :spec diff --git a/TODO b/TODO index 4c7025c..0f1ce39 100644 --- a/TODO +++ b/TODO @@ -1,7 +1,7 @@ - More integration specs - NFA -> DFA minimization using the subset construction algorithm (or another, if there is one). - Integration tests should be matching against both the DFA + NFA matching techniques - Google Protocol buffer output for DFA state table. Conversion of the buffer to a regex. - Unicode support - Empty regexs (//) should be matched by an empty string -- Get rid of NFA transition table in favor of DFA transition table \ No newline at end of file +- Get rid of NFA transition table in favor of DFA transition table diff --git a/lib/hopcroft.rb b/lib/hopcroft.rb index 17153c2..07e7aad 100644 --- a/lib/hopcroft.rb +++ b/lib/hopcroft.rb @@ -1,12 +1,12 @@ require "using" require "facets/kernel/returning" module Hopcroft extend Using - + Using.default_load_scheme = :autoload using :Regex using :Machine using :Converters end diff --git a/lib/hopcroft/converters.rb b/lib/hopcroft/converters.rb index ce4b029..6554761 100644 --- a/lib/hopcroft/converters.rb +++ b/lib/hopcroft/converters.rb @@ -1,8 +1,8 @@ module Hopcroft module Converters extend Using - + using :NfaStateCollection using :NfaToDfaConverter end -end \ No newline at end of file +end diff --git a/lib/hopcroft/converters/nfa_state_collection.rb b/lib/hopcroft/converters/nfa_state_collection.rb index 2e473a8..8c16d48 100644 --- a/lib/hopcroft/converters/nfa_state_collection.rb +++ b/lib/hopcroft/converters/nfa_state_collection.rb @@ -1,73 +1,73 @@ module Hopcroft module Converters class NfaStateCollection < Array class << self def nfa_to_dfa_states @nfa_to_dfa_states ||= {} end - + def register(obj, state) nfa_to_dfa_states[obj] ||= state end end - + def dfa_state @dfa_state ||= find_or_create_dfa_state end - + def find_or_create_dfa_state find_dfa_state || create_dfa_state end - + def find_dfa_state self.class.nfa_to_dfa_states[self] end - + def create_dfa_state returning new_dfa_state do |state| register(state) end end - + def new_dfa_state returning Machine::State.new do |state| state.start_state = has_start_state? state.final_state = has_final_state? end end - + def target_states(symbol) target_transitions = [] each do |state| additional_transitions = state.transitions.select { |t| t.symbol == symbol } target_transitions.concat(additional_transitions) end target_transitions.map { |t| t.state } end - + def has_start_state? any? { |s| s.start_state? } end - + def has_final_state? any? { |s| s.final_state? } end - + def sort sort_by { |state| state.id } end - + def ==(other) sort == other.sort end - + private def register(state) self.class.register(self, state) end end end -end \ No newline at end of file +end diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index d6bc380..f915fba 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,81 +1,81 @@ module Hopcroft module Converters class NfaToDfaConverter include Machine::StateMachineHelpers - + def initialize(nfa) @nfa = nfa @nfa_states = {} end - + attr_reader :nfa - + def convert start_state = [@nfa.start_state] @nfa_states = { start_state => false } - + returning Machine::StateMachine.new do |dfa| dfa.start_state = dfa_state_for(start_state) - + while nfa_state = unmarked_states.first mark_state(nfa_state) symbols.each do |sym| target_nfa_states = move(epsilon_closure(nfa_state), sym) - + if target_nfa_states.any? add_nfa_state(target_nfa_states) - + source = dfa_state_for(nfa_state) target = dfa_state_for(target_nfa_states) source.add_transition :symbol => sym, :state => target end end end end end - + private - + def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end - + def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end - + def mark_state(nfa_state) @nfa_states[nfa_state] = true end - + def symbols @symbols ||= @nfa.symbols end - + def move(nfa_states, symbol) to_collection(nfa_states).target_states(symbol) end - + def to_collection(nfa_states) if nfa_states.respond_to? :target_states nfa_states else NfaStateCollection.new(nfa_states) end end - + def dfa_state_for(nfa_states) to_collection(nfa_states).dfa_state end end end -end \ No newline at end of file +end diff --git a/lib/hopcroft/machine.rb b/lib/hopcroft/machine.rb index 47b3b37..8184cd2 100644 --- a/lib/hopcroft/machine.rb +++ b/lib/hopcroft/machine.rb @@ -1,18 +1,18 @@ module Hopcroft module Machine extend Using - + using :Identifiable using :TransitionTable using :NfaTransitionTable using :DfaTransitionTable using :State using :Transition using :StateMachine using :EpsilonTransition using :AnyCharTransition using :TableConverter using :TableDisplayer using :StateMachineHelpers end end diff --git a/lib/hopcroft/machine/dfa_transition_table.rb b/lib/hopcroft/machine/dfa_transition_table.rb index 3a88da0..3c5c623 100644 --- a/lib/hopcroft/machine/dfa_transition_table.rb +++ b/lib/hopcroft/machine/dfa_transition_table.rb @@ -1,42 +1,42 @@ module Hopcroft module Machine class DfaTransitionTable < TransitionTable class DuplicateStateError < StandardError; end - + def add_state_change(from, to, sym) self[from] ||= {} raise DuplicateStateError if self[from][sym] self[from][sym] = to end - + def has_state_change?(from, to, sym) super && self[from][sym] == to ? true : false end - + def target_for(state, sym) self[state] && self[state][sym] ? self[state][sym] : nil end - + def matches?(input_array, target = start_state) raise_if_no_start_state - + input_array.each do |char| target = target_for(target, char) return false unless target end - + final_state? target end - + alias_method :initial_state, :start_state alias_method :initial_states, :start_state alias_method :next_transitions, :target_for - + private - + def final_state?(target) target.final? end end end end diff --git a/lib/hopcroft/machine/identifiable.rb b/lib/hopcroft/machine/identifiable.rb index 85bd6a3..bf6aa67 100644 --- a/lib/hopcroft/machine/identifiable.rb +++ b/lib/hopcroft/machine/identifiable.rb @@ -1,40 +1,40 @@ module Hopcroft module Machine module Identifiable class << self def extended(mod) mod.extend ClassMethods mod.class_eval do include InstanceMethods end end - + alias_method :included, :extended end - + module ClassMethods def reset_counter! @counter = 1 end def next_counter returning counter do |c| @counter += 1 end end def counter @counter ||= 1 end end - + module InstanceMethods def track_id @id = self.class.next_counter end - + attr_reader :id end end end -end \ No newline at end of file +end diff --git a/lib/hopcroft/machine/nfa_transition_table.rb b/lib/hopcroft/machine/nfa_transition_table.rb index 73eab76..e0269bb 100644 --- a/lib/hopcroft/machine/nfa_transition_table.rb +++ b/lib/hopcroft/machine/nfa_transition_table.rb @@ -1,84 +1,84 @@ module Hopcroft module Machine class NfaTransitionTable < TransitionTable def start_state=(start_state) self[start_state] ||= {} super end - + # Create a transition without marking appropriate start states def add_state_change(from_state, to_state, transition_symbol) sym = transition_symbol self[from_state] ||= {} self[from_state][sym] ||= [] self[from_state][sym] << to_state end def has_state_change?(from_state, to_state, transition_symbol) super && self[from_state][transition_symbol].include?(to_state) end def targets_for(state, transition_sym) find_targets_matching(state, transition_sym) do |target| epsilon_states_following(target) end end def initial_states [start_state] + epsilon_states_following(start_state) end def next_transitions(states, sym) states.map { |s| targets_for(s, sym) }.compact.flatten end - + def matches?(input_array, current_states = initial_states) raise_if_no_start_state - + input_array.each do |sym| current_states = next_transitions(current_states, sym.to_sym) end current_states.any? { |state| state.final? } end - + def symbols values.map { |v| v.keys }.flatten.uniq.reject { |sym| sym == EpsilonTransition } end - + private def epsilon_states_following(state) find_targets_matching(state, EpsilonTransition) do |target| epsilon_states_following(target) end end - + def find_targets_matching(state, transition_sym, &recursion_block) returning Array.new do |a| direct_targets = find_targets_for(state, transition_sym) a.concat(direct_targets) - + direct_targets.each do |target| a.concat(recursion_block.call(target)) end end end - + def find_targets_for(state, transition_sym) returning Array.new do |a| if state = self[state] if state[transition_sym] a.concat(state[transition_sym]) end if state[AnyCharTransition] && transition_sym != EpsilonTransition a.concat(state[AnyCharTransition]) end end end end end end end diff --git a/lib/hopcroft/machine/state.rb b/lib/hopcroft/machine/state.rb index e5e63f5..5ab31b3 100644 --- a/lib/hopcroft/machine/state.rb +++ b/lib/hopcroft/machine/state.rb @@ -1,132 +1,132 @@ module Hopcroft module Machine class State include Identifiable def initialize(options={}) track_id - + @start_state = options[:start_state] if options.has_key?(:start_state) @final_state = options[:final] if options.has_key?(:final) - + assign_name(options) end attr_reader :name alias_method :to_s, :name def inspect "#{name} {start: #{start_state?}, final: #{final_state?}, transitions: #{transitions.size}}" end def transitions @transitions ||= [] end attr_writer :transitions - + def epsilon_transitions transitions.select { |t| t.epsilon_transition? } end - + def number_of_transitions transitions.size end # Accepts the following hash arguments: # # :machine => m (optional). Links current state to start state of machine # given with an epsilon transition. # :start_state => true | false. Make the state a start state. Defaults to false # :final => true | false. Make the state a final state. Defaults to false # :state => a_state (if none passed, a new one is constructed) # :symbol => Symbol to transition to. # :epsilon => An Epsilon Transition instead of a regular symbol transition # :any => An any symbol transition. Equivalent to a regex '.' # def add_transition(args={}) args[:start_state] = false unless args.has_key?(:start_state) if args[:machine] machine = args[:machine] args[:state] = machine.start_state args[:state].start_state = false args[:epsilon] = true else args[:state] ||= State.new(args) end - + returning args[:state] do |state| transitions << transition_for(args, state) yield(state) if block_given? state end end def transition_for(args, state) if args[:epsilon] EpsilonTransition.new(state) elsif args[:any] AnyCharTransition.new(state) else Transition.new(args[:symbol], state) end end def start_state? @start_state.equal?(false) ? false : true end - + attr_writer :start_state - + def final_state? @final_state ? true : false end alias_method :final?, :final_state? attr_writer :final_state - + def substates(excluded_states = []) returning [] do |list| follow_states.each do |state| unless excluded_states.include?(state) excluded_states << state - + list.push state list.concat(state.substates(excluded_states)) end end end end - + def follow_states(excluded_states = []) transitions.map { |t| t.state }.reject { |s| excluded_states.include?(s) } end def add_transitions_to_table(table) transitions.each do |transition| to = transition.to unless table.has_state_change?(self, to, transition.symbol) table.add_state_change(self, to, transition.symbol) transition.to.add_transitions_to_table(table) end end end def deep_clone returning clone do |c| c.transitions = transitions.map { |t| t.deep_clone } end end private def assign_name(options) @name = options[:name] ? options[:name] : "State #{@id}" end end end end diff --git a/lib/hopcroft/machine/state_machine.rb b/lib/hopcroft/machine/state_machine.rb index ebb9701..27a6580 100644 --- a/lib/hopcroft/machine/state_machine.rb +++ b/lib/hopcroft/machine/state_machine.rb @@ -1,52 +1,52 @@ module Hopcroft module Machine class StateMachine def initialize(start_state = State.new) @start_state = start_state end attr_accessor :start_state def states [start_state, start_state.substates].flatten end def final_states states.select { |s| s.final? } end def matches_string?(str) matches_array? str.split("") end - + alias_method :matches?, :matches_string? - + def matches_array?(array) state_table.matches?(array) end def nfa_state_table returning NfaTransitionTable.new do |table| table.start_state = start_state start_state.add_transitions_to_table(table) end end alias_method :state_table, :nfa_state_table def deep_clone returning clone do |c| c.start_state = c.start_state.deep_clone end end - + def symbols state_table.symbols end - + def to_dfa Converters::NfaToDfaConverter.new(self).convert end end end end diff --git a/lib/hopcroft/machine/state_machine_helpers.rb b/lib/hopcroft/machine/state_machine_helpers.rb index 26adbc3..e4d8b04 100644 --- a/lib/hopcroft/machine/state_machine_helpers.rb +++ b/lib/hopcroft/machine/state_machine_helpers.rb @@ -1,34 +1,34 @@ module Hopcroft module Machine module StateMachineHelpers def epsilon_closure(state_or_state_list) if state_or_state_list.is_a?(Machine::State) epsilon_closure_for_state(state_or_state_list) else epsilon_closure_for_state_list(state_or_state_list) end end private - + def epsilon_closure_for_state_list(state_list) returning [] do |return_list| state_list.each do |state| return_list.concat(epsilon_closure_for_state(state)) end end end def epsilon_closure_for_state(state, seen_states = []) returning [] do |set| if !seen_states.include?(state) set << state state.epsilon_transitions.each do |transition| set.concat(epsilon_closure_for_state(transition.state, seen_states << state)) end end end end end end end diff --git a/lib/hopcroft/machine/transition.rb b/lib/hopcroft/machine/transition.rb index 2dac679..542617a 100644 --- a/lib/hopcroft/machine/transition.rb +++ b/lib/hopcroft/machine/transition.rb @@ -1,22 +1,22 @@ module Hopcroft module Machine class Transition def initialize(symbol, state) @symbol = symbol.respond_to?(:to_sym) ? symbol.to_sym : symbol @state = state end attr_reader :symbol attr_reader :state alias_method :to, :state def deep_clone self.class.new(symbol, state.deep_clone) end - + def epsilon_transition? symbol == EpsilonTransition end end end end diff --git a/lib/hopcroft/machine/transition_table.rb b/lib/hopcroft/machine/transition_table.rb index 4e2b709..6fd5ac0 100644 --- a/lib/hopcroft/machine/transition_table.rb +++ b/lib/hopcroft/machine/transition_table.rb @@ -1,39 +1,39 @@ module Hopcroft module Machine class TransitionTable < Hash class MissingStartState < StandardError; end - + attr_accessor :start_state - + def add_state_change(from, to, sym) raise NotImplementedError end - + def has_state_change?(from, to, sym) self[from] && self[from][sym] end - + def to_hash Hash.new(self) end - + def inspect TableDisplayer.new(self).to_s end - + def matches?(input_array) raise NotImplementedError end - + def matched_by?(*args) matches?(*args) end - + private - + def raise_if_no_start_state raise MissingStartState unless start_state - end + end end end -end \ No newline at end of file +end diff --git a/lib/hopcroft/regex.rb b/lib/hopcroft/regex.rb index 2f7fc1c..86fbb2d 100644 --- a/lib/hopcroft/regex.rb +++ b/lib/hopcroft/regex.rb @@ -1,40 +1,40 @@ require "treetop" module Hopcroft module Regex SPECIAL_CHARS = [ DOT = ".", PLUS = "+", QUESTION = "?", STAR = "*", OPEN_BRACKET = "[", CLOSE_BRACKET = "]", ESCAPE_CHAR = "\\", ALTERNATION = "|" ] extend Using using :Base using :Char using :KleenStar using :Plus using :Dot using :CharacterClass using :OptionalSymbol using :Concatenation using :Alternation using :SyntaxNodes using :Parser - + def self.parse(from_string) Parser.parse(from_string) end - + def self.compile(string) returning parse(string) do |regex| regex.compile end end end end diff --git a/lib/hopcroft/regex/base.rb b/lib/hopcroft/regex/base.rb index e0acb12..5cd45b5 100644 --- a/lib/hopcroft/regex/base.rb +++ b/lib/hopcroft/regex/base.rb @@ -1,62 +1,62 @@ module Hopcroft module Regex class Base def initialize(expr) @expression = expr end - + attr_reader :expression def ==(other) other.respond_to?(:to_regex_s) && to_regex_s == other.to_regex_s end def matches?(str) to_machine.matches? str end - + alias_method :matched_by?, :matches? def +(other) Concatenation.new(self, other) end def |(other) Alternation.new(self, other) end def to_regexp Regexp.new(to_regex_s) end alias_method :to_regex, :to_regexp def to_nfa new_machine do |m, start_state| build_machine(start_state) end end - + def to_dfa to_nfa.to_dfa end - + def to_machine to_nfa end - + def compile @dfa ||= to_dfa end private def new_machine returning Machine::StateMachine.new do |machine| yield machine, machine.start_state if block_given? end end end end end diff --git a/lib/hopcroft/regex/character_class.rb b/lib/hopcroft/regex/character_class.rb index 608cb60..9af7b16 100644 --- a/lib/hopcroft/regex/character_class.rb +++ b/lib/hopcroft/regex/character_class.rb @@ -1,75 +1,75 @@ module Hopcroft module Regex class CharacterClass < Base class InvalidCharacterClass < StandardError; end class << self def new(*strs) if strs.size == 1 && one_char_long?(strs.first) Char.new(strs.first) else super end end private def one_char_long?(str) str.size == 1 || (str.size == 2 && str[0] == "\\"[0]) end end def initialize(*strs) @expressions = strs raise InvalidCharacterClass if invalid_expression? end def build_machine(start_state) each_symbol do |sym| start_state.add_transition :symbol => sym, :final => true end end def each_symbol(&block) symbols.each(&block) end def symbols @expressions.map { |expr| symbols_for_expr(expr) }.flatten end def to_regex_s "#{OPEN_BRACKET}#{expression_regex}#{CLOSE_BRACKET}" end private - + def symbols_for_expr(expr) if expr.include?("-") Range.new(*expr.split("-")).to_a.map { |e| e.to_s } else expr end end - + def expression_regex @expressions.join("") end def valid_expression? @expressions.all? do |expr| if expr.include?("-") one, two = expr.split("-") two > one else true end end end def invalid_expression? !valid_expression? end end end end diff --git a/lib/hopcroft/regex/optional_symbol.rb b/lib/hopcroft/regex/optional_symbol.rb index 59b7d73..b58c8a5 100644 --- a/lib/hopcroft/regex/optional_symbol.rb +++ b/lib/hopcroft/regex/optional_symbol.rb @@ -1,16 +1,16 @@ module Hopcroft module Regex class OptionalSymbol < Base def to_regex_s "#{expression.to_regex_s}#{QUESTION}" end def build_machine(start) start.final_state = true - + machine = @expression.to_machine start.add_transition :machine => machine end end end end diff --git a/lib/hopcroft/regex/parser.rb b/lib/hopcroft/regex/parser.rb index 2a21d61..2fe6c2d 100644 --- a/lib/hopcroft/regex/parser.rb +++ b/lib/hopcroft/regex/parser.rb @@ -1,39 +1,39 @@ require "treetop" Treetop.load File.dirname(__FILE__) + "/regex_parser" module Hopcroft module Regex class Parser class ParseError < StandardError; end def self.parse(str, debugging = false) obj = new obj.debug = debugging obj.parse_and_eval(str) end def initialize @parser = Regex::TreetopRegexParser.new end def parse(str) @parser.parse(str) end - + def debugging? @debug ? true : false end - + attr_writer :debug - + def parse_and_eval(str) if parse = parse(str) parse.eval else puts @parser.inspect if debugging? raise ParseError, "could not parse the regex '#{str}'" end end end end end diff --git a/lib/hopcroft/regex/regex_parser.treetop b/lib/hopcroft/regex/regex_parser.treetop index 7180511..dcd2667 100644 --- a/lib/hopcroft/regex/regex_parser.treetop +++ b/lib/hopcroft/regex/regex_parser.treetop @@ -1,168 +1,168 @@ # # This grammar is taken from GNU's grep grammar, with slight modifications. It doesn't # support backreferencing, metachars, negated character classes, repetion # with {n,m}, etc. - although there is no reason that it couldn't. -# +# # In addition, GNU's grep grammar is modified for an LL parser. LL parsers can't # process left recursion without under going left factorization: -# +# # See: # http://treetop.rubyforge.org/pitfalls_and_advanced_techniques.html # http://en.wikipedia.org/wiki/Left_recursion#Removing_immediate_left_recursion -# -# +# +# # From GNU grep: # The grammar understood by the parser is as follows. -# +# # regexp: # regexp OR branch # branch -# +# # branch: # branch closure # closure -# +# # closure: # closure QMARK # closure STAR # closure PLUS # closure REPMN # atom -# +# # atom: # <normal character> # <multibyte character> # ANYCHAR # MBCSET # CSET # BACKREF # BEGLINE # ENDLINE # BEGWORD # ENDWORD # LIMWORD # NOTLIMWORD # CRANGE # LPAREN regexp RPAREN # <empty> -# +# # The parser builds a parse tree in postfix form in an array of tokens. module Hopcroft module Regex grammar TreetopRegex rule regex branch regex_prime <SyntaxNodes::Regex> end - + rule regex_prime OR branch subexpression:regex_prime <SyntaxNodes::Alternation> / epsilon end - + rule branch closure branch_prime <SyntaxNodes::Branch> end rule branch_prime closure branch_prime <SyntaxNodes::Concatenation> / epsilon end - + rule epsilon "" <SyntaxNodes::Epsilon> end - + rule closure atom closure_prime <SyntaxNodes::Closure> end - + rule closure_prime kleen_star / one_or_more_expr / optional_expr / epsilon end - + rule kleen_star "*" <SyntaxNodes::KleenStar> end - + rule one_or_more_expr "+" <SyntaxNodes::OneOrMoreExpression> end - + rule optional_expr "?" <SyntaxNodes::OptionalExpression> end - + rule atom parenthesized_expression / dot / character_class / single_char end - + rule dot "." <SyntaxNodes::Dot> end - + rule parenthesized_expression LEFT_PARENS regex RIGHT_PARENS <SyntaxNodes::ParenthesizedExpression> end rule character_class LEFT_BRACKET inner_char_class RIGHT_BRACKET <SyntaxNodes::CharacterClass> end - + rule inner_char_class inner_char_class_expr+ <SyntaxNodes::MultipleInnerCharClass> end - + rule inner_char_class_expr one:single_char "-" two:single_char <SyntaxNodes::TwoCharClass> / single_char <SyntaxNodes::OneCharClass> end - + rule single_char non_special_char / escaped_char end - + rule non_special_char !("(" / ")" / "[" / "+" / "?" / "+" / "]" / "|" / "*" / "\\") any_char:ANY_CHAR <SyntaxNodes::Char> end - + rule escaped_char ESCAPE any_char:ANY_CHAR <SyntaxNodes::Char> end - + rule OR "|" end - + rule ANY_CHAR . end - + rule LEFT_BRACKET "[" end - + rule RIGHT_BRACKET "]" end - + rule ESCAPE "\\" end - + rule LEFT_PARENS "(" end - + rule RIGHT_PARENS ")" end end end end diff --git a/lib/hopcroft/regex/syntax_nodes.rb b/lib/hopcroft/regex/syntax_nodes.rb index 0f16f7f..046e2ba 100644 --- a/lib/hopcroft/regex/syntax_nodes.rb +++ b/lib/hopcroft/regex/syntax_nodes.rb @@ -1,125 +1,125 @@ module Hopcroft module Regex module SyntaxNodes class Base < ::Treetop::Runtime::SyntaxNode; end - + class Regex < Base def eval if tuple = regex_prime.eval tuple.first.new(branch.eval, tuple.last) else branch.eval end end end - + module Char def eval Hopcroft::Regex::Char.new(any_char.text_value) end end - + class Branch < Base def eval if branch_prime.eval closure.eval + branch_prime.eval else closure.eval end end end - + class Alternation < Base def eval if sub = subexpression.eval subexpression = sub.first.new(branch.eval, sub.last) [Hopcroft::Regex::Alternation, subexpression] else [Hopcroft::Regex::Alternation, branch.eval] end end end class Concatenation < Base def eval if other = branch_prime.eval closure.eval + branch_prime.eval else closure.eval end end end - + class Closure < Base def eval if closure_prime.eval closure_prime.eval.new(atom.eval) else atom.eval end end end - + class KleenStar < Base def eval Hopcroft::Regex::KleenStar end end - + class OptionalExpression < Base def eval Hopcroft::Regex::OptionalSymbol end end - + class OneOrMoreExpression < Base def eval Hopcroft::Regex::Plus end end - + class CharacterClass < Base def eval Hopcroft::Regex::CharacterClass.new(*inner_char_class.eval) end end - + class MultipleInnerCharClass < Base def eval elements.map { |e| e.eval } end end - + class TwoCharClass < Base def eval "#{one.text_value}-#{two.text_value}" end end - + module OneCharClass def eval text_value end end - + class Epsilon < Base def eval nil end end - + class ParenthesizedExpression < Base def eval regex.eval end end - + class Dot < Base def eval Hopcroft::Regex::Dot.new end end end end end - + diff --git a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb index 5a777b6..c0d5b63 100644 --- a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb +++ b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb @@ -1,177 +1,177 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Converters describe NfaToDfaConverter do before do @nfa = Machine::StateMachine.new end - + it "should take an state machine" do NfaToDfaConverter.new(@nfa).nfa.should equal(@nfa) end - + describe "conversion" do before do @converter = NfaToDfaConverter.new(@nfa) end - + it "should build a new state machine" do @converter.convert.should be_a_kind_of(Machine::StateMachine) end - + it "should have a start state" do @converter.convert.start_state.should_not be_nil end - + it "should keep a machine with a start state + no other states" do @converter.convert.start_state.transitions.should == [] end - + describe "with a dfa: state1(start) -> state2" do it "should create a new machine a transition" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end - + it "should create the new machine with the symbol :foo" do @nfa.start_state.add_transition :symbol => :foo - + conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:foo) end - + it "should use the correct symbol" do @nfa.start_state.add_transition :symbol => :bar - + conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:bar) end - + it "should not have an identical (object identical) start state" do conversion = @converter.convert @nfa.start_state.should_not equal(conversion.start_state) end - + it "should not have the start state as a final state" do @nfa.start_state.add_transition :symbol => :foo, :final => true conversion = @converter.convert conversion.start_state.should_not be_a_final_state end - + it "should have the final state as final" do @nfa.start_state.add_transition :symbol => :foo, :final => true conversion = @converter.convert conversion.start_state.transitions.first.state.should be_final end - + it "should not have the final state as a start state" do @nfa.start_state.add_transition :symbol => :foo, :final => true conversion = @converter.convert conversion.start_state.transitions.first.state.should_not be_a_start_state end end - + describe "a dfa with state1 -> state2 -> state3" do before do state2 = @nfa.start_state.add_transition :symbol => :foo state3 = state2.add_transition :symbol => :bar end - + it "should have a transition to state2" do conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end - + it "should have a transition to state3" do conversion = @converter.convert conversion.start_state.transitions.first.state.transitions.size.should == 1 end end - + describe "a dfa with a start state which loops back to itself (on a sym)" do before do start_state = @nfa.start_state start_state.add_transition :symbol => :f, :state => start_state - + @conversion = @converter.convert end - + it "should have a start state" do @conversion.start_state.should_not be_nil end - + it "should have one transition on the start state" do @conversion.start_state.transitions.size.should == 1 end - + it "should transition back to itself" do @conversion.start_state.transitions.first.state.should equal(@conversion.start_state) end end - + describe "an nfa with start state leading to two different states on the same symbol" do before do @nfa.start_state.add_transition :symbol => :a @nfa.start_state.add_transition :symbol => :a - + @conversion = @converter.convert end - + it "should only have one transition out of the start state" do @conversion.start_state.transitions.size.should == 1 end end - + describe "an NFA with an epsilon transition (start -> a -> epsilon -> b)" do before do two = @nfa.start_state.add_transition :symbol => :a three = two.add_transition :symbol => Machine::EpsilonTransition four = three.add_transition :symbol => :b - + @conversion = @converter.convert end - + it "should have one transition coming from the start state" do @conversion.start_state.number_of_transitions.should == 1 end - + it "should have the first transition on an a" do @conversion.start_state.transitions.first.symbol.should equal(:a) end - + it "should have a second transition to a b" do second_state = @conversion.start_state.transitions.first.state second_state.transitions.size.should == 1 second_state.transitions.first.symbol.should equal(:b) end end - + describe "with an epsilon transition on the same symbol to two different final states" do before do two = @nfa.start_state.add_transition :symbol => :a three = @nfa.start_state.add_transition :symbol => :a - + @conversion = @converter.convert end - + it "should have only one transition out of the start state" do @conversion.start_state.transitions.size.should == 1 end - + it "should have the transition out of the start state on the symbol" do @conversion.start_state.transitions.first.symbol.should == :a end - + it "should transition to a new state with no transitions" do target_state = @conversion.start_state.transitions.first.state - + target_state.transitions.should == [] end end end end end -end \ No newline at end of file +end diff --git a/spec/hopcoft/integration_spec.rb b/spec/hopcoft/integration_spec.rb index b2d1b60..2f8615a 100644 --- a/spec/hopcoft/integration_spec.rb +++ b/spec/hopcoft/integration_spec.rb @@ -1,173 +1,173 @@ require File.expand_path(File.dirname(__FILE__) + "/../spec_helper") module Hopcroft describe "Integration tests" do describe "the regex /a/" do before do @regex = Regex.compile("a") end - + it "should match 'a'" do @regex.should be_matched_by("a") end - + it "should not match 'b'" do @regex.should_not be_matched_by("b") end - + it "should not match 'abasdfasdf'" do @regex.should_not be_matched_by('abasdfasdf') end end - + describe "the regex /ab/" do before do @regex = Regex.compile("ab") end - + it "should match 'ab'" do @regex.should be_matched_by("ab") end - + it "should not match 'x'" do @regex.should_not be_matched_by("x") end - + it "should not match 'ba'" do @regex.should_not be_matched_by("ba") end end - + describe "the regex /a*/" do before do @regex = Regex.compile("a*") end - + it "should be matched by 'a'" do @regex.should be_matched_by("a") end - + it "should be matched by the empty string" do @regex.should be_matched_by("") end - + it "should be matched by 'aa'" do @regex.should be_matched_by("aa") end - + it "should be matched by 'aaa'" do @regex.should be_matched_by("aaa") end - + it "should not be matched by 'aab'" do @regex.should_not be_matched_by("aab") end end - + describe "the regex /a+/" do before do @regex = Regex.compile("a+") end - + it "should be matched by 'a'" do @regex.should be_matched_by("a") end - + it "should NOT be matched by the empty string" do @regex.should_not be_matched_by("") end - + it "should be matched by 'aa'" do @regex.should be_matched_by("aa") end - + it "should not be matched by 'aab'" do @regex.should_not be_matched_by("aab") end - + it "should be matched by 'aaa'" do @regex.matches?("aaa") @regex.should be_matched_by("aaa") end end - + describe "the regex /a|b/" do before do @regex = Regex.compile("a|b") end - + it "should be matched by an 'a'" do @regex.should be_matched_by("a") end - + it "should be matched by a 'b'" do @regex.should be_matched_by("b") end - + it "should not be matched by a 'c'" do @regex.should_not be_matched_by("c") end - + it "should not be matched with the string 'ab'" do @regex.matched_by?("ab") @regex.should_not be_matched_by("ab") end end - + describe "the regex /(a|b)+/" do before do @regex = Regex.compile("(a|b)+") end - + it "should not match the empty string" do @regex.should_not be_matched_by("") end - + it "should match an a" do @regex.should be_matched_by("a") end - + it "should match 'b'" do @regex.should be_matched_by("b") end - + it "should match 'aaa'" do @regex.should be_matched_by("aaa") end - + it "should match 'bbb'" do @regex.should be_matched_by("bbb") end - + it "should match 'ababababbbaaa'" do @regex.should be_matched_by('ababababbbaaa') end - + it "should not be matched if it contains a different char" do @regex.should_not be_matched_by("ababbbbaacaab") end end - + describe "the regex (a|b)+x" do before do @regex = Regex.compile("(a|b)+x") end - + it "should match 'ax'" do @regex.should be_matched_by("ax") end - + it "should match 'bx'" do @regex.should be_matched_by("bx") end - + it "should match 'ababx'" do @regex.should be_matched_by("ababx") end - + it "should not match 'x'" do @regex.should_not be_matched_by("x") end end end end diff --git a/spec/hopcoft/machine/dfa_transition_table_spec.rb b/spec/hopcoft/machine/dfa_transition_table_spec.rb index 5f8c7b1..a7e8297 100644 --- a/spec/hopcoft/machine/dfa_transition_table_spec.rb +++ b/spec/hopcoft/machine/dfa_transition_table_spec.rb @@ -1,185 +1,185 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe DfaTransitionTable do before do @table = DfaTransitionTable.new @state = State.new end - + it "should have the start state as assignable" do @table.start_state = @state @table.start_state.should equal(@state) end - + describe "adding state changes" do before do @state_two = State.new end - + it "should be able to add a state change with a symbol" do @table.add_state_change(@state, @state_two, :symbol) @table.has_state_change?(@state, @state_two, :symbol).should be_true end - + it "should not have a state change if none are provided" do @table.has_state_change?(@state, @state_two, :symbol).should be_false end - + it "should not match the state change if with a different sym" do @table.add_state_change(@state, @state_two, :symbol) @table.has_state_change?(@state, @state_two, :bar).should be_false end - + it "should not match the state change with a different starting state" do @table.add_state_change(@state, @state_two, :symbol) @table.has_state_change?(mock('different state'), @state_two, :symbol).should be_false end - + it "should not match the state change with a different finishing state" do @table.add_state_change(@state, @state_two, :symbol) @table.has_state_change?(@state, mock('a different state'), :symbol).should be_false end - + it "should raise an error if a state change for the state & symbol has already been provided" do @table.add_state_change(@state, @state_two, :symbol) - + lambda { @table.add_state_change(@state, mock("another target"), :symbol) }.should raise_error(DfaTransitionTable::DuplicateStateError) end end - + describe "target_for" do before do @state_two = State.new end - + it "should be the to symbol of the state change" do @table.add_state_change(@state, @state_two, :symbol) @table.target_for(@state, :symbol).should == @state_two end - + it "should return nil if it cannot find the state" do @table.add_state_change(@state, @state_two, :symbol) @table.target_for(mock("a different state"), :symbol).should be_nil end - + it "should return nil if it cannot find the symbol" do @table.add_state_change(@state, @state_two, :symbol) @table.target_for(@state, :foo).should be_nil end end - + describe "to_hash" do it "should return a hash" do @table.to_hash.should be_a_kind_of(Hash) end - + it "should return a hash constructed from the table" do Hash.should_receive(:new).with(@table) @table.to_hash end end - + describe "initial_states" do it "should be the start state" do @table.start_state = @state @table.initial_state.should equal(@state) end end - + describe "next_transitions" do it "should be an alias for target_for" do @table.method(:next_transitions).should == @table.method(:target_for) end end - + describe "matches?" do it "should raise an error if there is no start state" do lambda { @table.matches?("foo") }.should raise_error(DfaTransitionTable::MissingStartState) end - + describe "with a start state which is a final state, with no transitions" do before do @state = State.new(:final => true) @table.start_state = @state end - + it "should match the start state with no input chars" do @table.should be_matched_by([]) end - + it "should not match when given an input symbol" do @table.should_not be_matched_by(["a"]) end end - + describe "with only a start state & no final states" do before do @state = State.new(:final => false) @table.start_state = @state end - + it "should not match with no input" do @table.should_not be_matched_by([]) end - + it "should not match when given an input symbol" do @table.should_not be_matched_by(["a"]) end end - + describe "with a start state which leads to a final state" do before do @state = State.new @final_state = State.new(:final => true) - + @table.start_state = @state @table.add_state_change @state, @final_state, "a" end - + it "should not match when given no input" do @table.should_not be_matched_by([]) end - + it "should match when given the one char" do @table.should be_matched_by(["a"]) end - + it "should not match when given a different char" do @table.should_not be_matched_by(["b"]) end - + it "should not match when given the input symbol repeatedly" do @table.should_not be_matched_by(["a", "a"]) end - + it "should return false if it does not match" do @table.matched_by?(["a", "a"]).should be_false end end end - + describe "inspect" do it "should call TableDisplayer" do TableDisplayer.should_receive(:new) @table.inspect end - + it "should output a display with rows + columns (it should not raise an error)" do state1, state2 = State.new, State.new - + @table.add_state_change(state1, state2, :a_sym) - + lambda { @table.inspect }.should_not raise_error end end end end -end \ No newline at end of file +end diff --git a/spec/hopcoft/machine/nfa_transition_table_spec.rb b/spec/hopcoft/machine/nfa_transition_table_spec.rb index b4045ee..7001b88 100644 --- a/spec/hopcoft/machine/nfa_transition_table_spec.rb +++ b/spec/hopcoft/machine/nfa_transition_table_spec.rb @@ -1,299 +1,299 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe NfaTransitionTable do describe "adding a state change" do before do @table = NfaTransitionTable.new end it "should create a two dimensional entry, with [from_state][transition] = [to_state]" do from = mock(State, :start_state? => false) to = mock(State, :start_state? => false) @table.add_state_change(from, to, :a) - + @table.targets_for(from, :a).should == [to] end it "should be able to use strings when finding a start state" do from = mock State, :start_state? => true, :final? => false to = mock State, :start_state? => false, :final? => true @table.add_state_change(from, to, :a) @table.start_state = from - + @table.matches?("a").should be_true end it "should be able to use multiple transitions from the same state" do from = mock(State, :start_state? => false) first_result = mock(State, :start_state? => false) second_result = mock(State, :start_state? => false) @table.start_state = from @table.add_state_change(from, first_result, :a) @table.add_state_change(from, second_result, :b) - + @table.targets_for(from, :a).should == [first_result] @table.targets_for(from, :b).should == [second_result] end it "should be able to use the same transition symbol to different states (for an NFA)" do from = mock(State, :start_state? => false) first_result = mock(State, :start_state? => false) second_result = mock(State, :start_state? => false) @table.add_state_change(from, first_result, :a) @table.add_state_change(from, second_result, :a) - + @table.targets_for(from, :a).should == [first_result, second_result] end it "should have a transition for an 'any' transition" do from = State.new :start_state => true to = from.add_transition :any => true transition = from.transitions.first.symbol @table.add_state_change from, to, transition @table.targets_for(from, :a).should == [to] end end describe "targets_for" do before do @table = NfaTransitionTable.new @state = mock(State, :start_state? => false, :final? => false) @transition = :foo end it "should reutrn an empty array if it indexes the state, but no transitions for that state" do @table.add_state_change(@state, @state, :foo) @table.targets_for(@state, :bar).should == [] end it "should return an empty array if it does not index the state" do @table.targets_for(@state, :foo).should == [] end end describe "matching a symbol" do before do @table = NfaTransitionTable.new end it "should match if one symbol in the table, and the symbol is given" do start_state = mock(State, :final? => false, :start_state? => true) final_state = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change(start_state, final_state, :foo) @table.matches?([:foo]).should be_true end it "should not match when it cannot index the transition" do start_state = mock(State, :final? => false, :start_state? => true) final_state = mock(State, :final? => true, :start_state? => false) - + @table.start_state = start_state @table.add_state_change(start_state, final_state, :foo) @table.matches?([:bar]).should be_false end it "should not match if the last state in the input is not a final state" do start_state = mock(State, :final? => false, :start_state? => true) final_state = mock(State, :final? => false, :start_state? => false) - + @table.start_state = start_state @table.add_state_change(start_state, final_state, :foo) @table.matches?([:foo]).should be_false end it "should raise an error if there is no start state" do lambda { @table.matches?([:foo]) }.should raise_error(NfaTransitionTable::MissingStartState) end it "should match when following two symbols" do start_state = mock(State, :final? => false, :start_state? => true) state_one = mock(State, :final? => false, :start_state? => false) state_two = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_one, :one @table.add_state_change state_one, state_two, :two @table.matches?([:one, :two]).should be_true end it "should not match when following two symbols, and the last is not a final state" do start_state = mock(State, :final? => false, :start_state? => true) state_one = mock(State, :final? => false, :start_state? => false) state_two = mock(State, :final? => false, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_one, :one @table.add_state_change state_one, state_two, :two @table.matches?([:one, :two]).should be_false end it "should match a NFA, where a start state leads to one of two possible final states" do start_state = mock(State, :final? => false, :start_state? => true) state_one = mock(State, :final? => false, :start_state? => false) state_two = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_one, :one @table.add_state_change start_state, state_two, :one @table.matches?([:one]).should be_true end it "should not match when the one state does not transition to the other" do start_state = mock(State, :final? => false, :start_state? => true) state_one = mock(State, :final? => false, :start_state? => false) state_two = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_one, :one @table.add_state_change start_state, state_two, :two @table.matches?([:one, :two]).should be_false end it "should not consume any chars under an epsilon transition" do start_state = mock(State, :final? => false, :start_state? => true) state_two = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_two, EpsilonTransition @table.matches?([]).should be_true end end describe "inspect" do before do @table = NfaTransitionTable.new @displayer = mock TableDisplayer end it "should output a state table" do TableDisplayer.should_receive(:new).with(@table).and_return @displayer @displayer.should_receive(:to_s) - + @table.inspect end it "should display 'Empty table' when empty" do @table.inspect.should == "\nEmpty table" end it "should be able to display a start state with no transitions" do start_state = State.new(:start_state => true, :name => "Foo") @table.start_state = start_state @table.inspect.should include("Foo") end end describe "to_hash" do it "should return a hash" do NfaTransitionTable.new.to_hash.class.should == Hash end end - + describe "initial states" do describe "for a start_state to an epsilon transition" do # +--------------+--------------------------------------+-------------+ # | | Hopcroft::Machine::EpsilonTransition | a | # +--------------+--------------------------------------+-------------+ # | -> State 207 | State 208 | | # | State 208 | | * State 209 | # +--------------+--------------------------------------+-------------+ before do @state1 = State.new :start_state => true, :name => "State 1" @state2 = State.new :start_state => false, :name => "State 2" @state3 = State.new :start_state => false, :name => "State 3", :final_state => true - + @table = NfaTransitionTable.new @table.add_state_change @state1, @state2, EpsilonTransition @table.add_state_change @state2, @state3, :a @table.start_state = @state1 end - + it "should have state 1 as an initial state (it is a start state)" do @table.initial_states.should include(@state1) end - + it "should have state 2 as an initial state (it has an epsilon transition from the start state)" do @table.initial_states.should include(@state2) end - + it "should not have state 3 as an initial state" do @table.initial_states.should_not include(@state3) end end end - + describe "symbols" do before do @table = NfaTransitionTable.new - + @state1 = State.new :start_state => true, :name => "State 1" @state2 = State.new :start_state => false, :name => "State 2" @state3 = State.new :start_state => false, :name => "State 3", :final_state => true end - + it "should have no symbols with no transitions" do @table.symbols.should == [] end - + it "should have no symbols with a start state, but no transitions" do @table.start_state = @state1 @table.symbols.should == [] end - + it "should report a regular symbol" do @table.start_state = @state1 @table.add_state_change @state1, @state2, :foo - + @table.symbols.should == [:foo] end - + it "should report several regular symbols" do @table.start_state = @state1 @table.add_state_change @state1, @state2, :foo @table.add_state_change @state2, @state3, :bar - + @table.symbols.should include(:foo) @table.symbols.should include(:bar) end - + it "should report a symbol only once" do @table.start_state = @state1 @table.add_state_change @state1, @state2, :foo @table.add_state_change @state2, @state3, :foo - + @table.symbols.should == [:foo] end - + it "should not report epsilon symbols" do @table.start_state = @state1 @table.add_state_change @state1, @state2, EpsilonTransition - + @table.symbols.should == [] end end end end end diff --git a/spec/hopcoft/machine/state_machine_helpers_spec.rb b/spec/hopcoft/machine/state_machine_helpers_spec.rb index 2230715..c73c384 100644 --- a/spec/hopcoft/machine/state_machine_helpers_spec.rb +++ b/spec/hopcoft/machine/state_machine_helpers_spec.rb @@ -1,83 +1,83 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe StateMachineHelpers do before do @obj = Object.new @obj.extend StateMachineHelpers end describe "epsilon_closure" do it "should be an empty list when given an empty list" do @obj.epsilon_closure([]).should == [] end it "should return the state when the state has no transitions" do state = State.new @obj.epsilon_closure([state]).should == [state] end it "should return an epsilon closure target" do state1 = State.new state2 = State.new - + state1.add_transition :state => state2, :epsilon => true - + @obj.epsilon_closure([state1]).should include(state2) end it "should not return a target with a state1 => state2 on a regular transition symbol" do state1 = State.new state2 = State.new state1.add_transition :symbol => :sym, :state => state2 @obj.epsilon_closure([state1]).should_not include(state2) end it "should follow epsilon targets from several states" do state1 = State.new state2 = State.new state1.add_transition :state => state2, :epsilon => true - + state3 = State.new state4 = State.new state3.add_transition :state => state4, :epsilon => true - + @obj.epsilon_closure([state1, state3]).should include(state2) @obj.epsilon_closure([state1, state3]).should include(state4) end it "should find multiple levels of epsilon transitions" do state1 = State.new state2 = State.new state3 = State.new - + state1.add_transition :state => state2, :epsilon => true state2.add_transition :state => state3, :epsilon => true @obj.epsilon_closure([state1]).should include(state2) @obj.epsilon_closure([state1]).should include(state3) end - + it "should not recur infinitely" do state = State.new - + state.add_transition :state => state, :epsilon => true - + @obj.epsilon_closure([state]).should include(state) end - + it "should not include the same state twice" do state = State.new - + state.add_transition :state => state, :epsilon => true - + @obj.epsilon_closure([state]).should == [state] end end end end end diff --git a/spec/hopcoft/machine/state_machine_spec.rb b/spec/hopcoft/machine/state_machine_spec.rb index d3d8ff3..2a65d36 100644 --- a/spec/hopcoft/machine/state_machine_spec.rb +++ b/spec/hopcoft/machine/state_machine_spec.rb @@ -1,123 +1,123 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe StateMachine do before do @machine = StateMachine.new end it "should have a start state when beginning" do @machine.start_state.should be_a_kind_of(State) end it "should be able to add a start state" do state = State.new - + @machine.start_state = state @machine.start_state.should equal(state) end - + it "should accept a start state in the constructor" do state = State.new machine = StateMachine.new(state) machine.start_state.should equal(state) end it "should be able to traverse a list of states" do state = State.new second_state = State.new state.add_transition(:symbol => :foo, :state => second_state) @machine.start_state = state @machine.states.should == [state, second_state] end describe "building the transition table" do before do @machine = StateMachine.new end - + it "should match a transition of the start state to another state" do start_state = @machine.start_state second_state = start_state.add_transition :symbol => :foo - + @machine.state_table.targets_for(start_state, :foo).should == [second_state] end - + it "should match multiple transitions on the same key (a NFA)" do start_state = @machine.start_state state_one = start_state.add_transition :symbol => :foo state_two = start_state.add_transition :symbol => :foo - + @machine.state_table.targets_for(start_state, :foo).should == [state_one, state_two] end - + it "should be able to have a state with a transition to itself" do start_state = @machine.start_state start_state.add_transition :symbol => :foo, :state => start_state - + @machine.state_table.targets_for(start_state, :foo).should == [start_state] end it "should add a start state with no transitions to the table" do start_state = @machine.start_state - + @machine.state_table.start_state.should == start_state end end describe "deep_copy" do before do @machine = StateMachine.new end it "should create a new instance" do @machine.deep_clone.should_not equal(@machine) end it "should have a cloned start state" do @machine.deep_clone.start_state.should_not equal(@machine.start_state) end it "should have the cloned start state as a final state if the original machine did" do @machine.start_state.final_state = true @machine.deep_clone.start_state.should be_a_final_state end it "should call deep_clone on the start state" do @machine.start_state.should_receive(:deep_clone) @machine.deep_clone end end - + describe "to_dfa" do before do @machine = StateMachine.new end - + it "should call the NFA to Dfa converter" do converter = mock 'converter', :convert => true - + Converters::NfaToDfaConverter.should_receive(:new).with(@machine).and_return converter @machine.to_dfa end - + it "should call convert" do converter = mock 'converter', :convert => true Converters::NfaToDfaConverter.stub!(:new).and_return(converter) - + converter.should_receive(:convert) @machine.to_dfa end - + it "should return a new state machine" do dfa = @machine.to_dfa dfa.should be_a_kind_of(StateMachine) dfa.should_not equal(@machine) end end end end end diff --git a/spec/hopcoft/machine/state_spec.rb b/spec/hopcoft/machine/state_spec.rb index 743d334..889ca06 100644 --- a/spec/hopcoft/machine/state_spec.rb +++ b/spec/hopcoft/machine/state_spec.rb @@ -1,321 +1,321 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe State do it "should set the start state on the first state to a start state" do state = State.new state.should be_a_start_state end it "should have no transitions to begin with" do s = State.new s.transitions.should == [] end - + it "should be able to add transitions" do s = State.new s.add_transition :symbol => :foo s.transitions.size.should == 1 end it "should be a start state" do s = State.new s.should be_a_start_state end it "should have start state assigned" do s = State.new s.start_state = false s.should_not be_a_start_state end it "should not be a final state by default" do s = State.new s.should_not be_a_final_state s.should_not be_final end it "should have the final state as assignable" do s = State.new s.final_state = true s.should be_a_final_state s.should be_final end describe "transitions" do before do @state = State.new end it "should create a transition when calling add_transition" do @state.add_transition :symbol => :foo @state.transitions.first.should be_a_kind_of(Transition) end it "should pass on the symbol to the transition" do @state.add_transition :symbol => :baz transition = @state.transitions.first transition.symbol.should == :baz end it "should construct a new state when none provided" do @state.add_transition :symbol => :foo transition = @state.transitions.first transition.state.should be_a_kind_of(State) end it "should not have the new state as the start state" do @state.add_transition :symbol => :foo transition = @state.transitions.first transition.state.should_not be_a_start_state end it "should be able to mark the new state as a final state" do @state.add_transition :symbol => :foo, :final => true transition = @state.transitions.first transition.state.should be_a_final_state end it "should take another state as the transition target" do state = mock('state', :null_object => true) @state.add_transition :symbol => :foo, :state => state transition = @state.transitions.first transition.state.should == state end it "should be able to add transitions recursively" do s1 = State.new s2 = State.new s1.add_transition :state => s2, :epsilon => true s2.add_transition :state => s1, :epsilon => true table = NfaTransitionTable.new s1.add_transitions_to_table(table) end - + describe "passed :machine => m" do before do @state = State.new @machine = StateMachine.new end - + it "should add a transition to another state machines first state" do other_machine_start_state = @machine.start_state - + @state.add_transition :machine => @machine @state.transitions.first.state.should == other_machine_start_state end - + it "should add the transition as an epsilon transition" do @state.add_transition :machine => @machine - + @state.transitions.first.should be_a_kind_of(EpsilonTransition) end - + it "should no longer have the other machines start state as a start state in this machine" do other_machine_start_state = @machine.start_state - + @state.add_transition :machine => @machine - + @state.transitions.first.state.should_not be_a_start_state end end end describe "name" do it "should take a name param" do state = State.new(:name => "foo") state.name.should == "foo" end it "should auto-assign a state #" do State.reset_counter! state = State.new state.name.should == "State 1" end it "should assign 'State 2' for the second state created" do State.reset_counter! State.new state2 = State.new state2.name.should == "State 2" end end describe "to_s" do it "should be aliased to the name" do s = State.new s.method(:name).should == s.method(:to_s) end end describe "inspect" do it "should display the name" do s = State.new(:name => "State 1") s.inspect.should include("State 1") end it "should show start state, final state, etc." do s = State.new(:name => "State 1", :start_state => true, :final => true) s.inspect.should == "State 1 {start: true, final: true, transitions: 0}" end it "should display the correct value for the start state" do s = State.new(:name => "State 1", :start_state => false, :final => true) s.inspect.should == "State 1 {start: false, final: true, transitions: 0}" end it "should display the correct value for the final state" do s = State.new(:name => "State 1", :start_state => true, :final => false) s.inspect.should == "State 1 {start: true, final: false, transitions: 0}" end it "should display 1 transition" do s = State.new(:name => "State 1", :start_state => true, :final => true) s.add_transition s.inspect.should == "State 1 {start: true, final: true, transitions: 1}" end end describe "deep_clone" do before do @state = State.new end it "should be of class State" do clone = @state.deep_clone clone.should be_a_kind_of(State) end it "should be a new instance" do clone = @state.deep_clone clone.should_not equal(@state) end it "should be a final state if the original was a final state" do @state.final_state = true clone = @state.deep_clone clone.should be_a_final_state end it "should not have the same transition objects" do @state.add_transition transition = @state.transitions.first clone = @state.deep_clone clone.transitions.first.should_not equal(transition) end it "should have one transition if the original had one transition" do @state.add_transition clone = @state.deep_clone clone.transitions.size.should == 1 end it "should have two transitions if the original had two transition" do @state.add_transition @state.add_transition clone = @state.deep_clone clone.transitions.size.should == 2 end it "should have a transition as a Transition object" do @state.add_transition clone = @state.deep_clone clone.transitions.first.should be_a_kind_of(Transition) end it "should call deep_clone on the transitions" do @state.add_transition @state.transitions.first.should_receive(:deep_clone) @state.deep_clone end end describe "substates" do before do @state = State.new end - + it "should have none with no transitions" do @state.substates.should == [] end - + it "should have a state which is linked to by a transition" do new_state = @state.add_transition :symbol => :foo @state.substates.should == [new_state] end - + it "should have multiple states" do one = @state.add_transition :symbol => :foo two = @state.add_transition :symbol => :foo - + @state.substates.should == [one, two] end it "should show states of the states (should find the states substates recursively)" do substate = @state.add_transition :symbol => :foo sub_substate = substate.add_transition :symbol => :foo @state.substates.should == [substate, sub_substate] end - + it "should work with recursive transitions" do @state.add_transition :state => @state - + @state.substates.should == [@state] end - + it "should not find duplicate states" do state2 = @state.add_transition state3 = state2.add_transition state4 = state3.add_transition - + state5 = state2.add_transition state4.add_transition :state => state5 - + @state.substates.should == [state2, state3, state4, state5] end - + it "should deal with infinite recursion on more than one level" do state2 = @state.add_transition state3 = state2.add_transition state3.add_transition :state => @state - + @state.substates.should == [state2, state3, @state] end end - + describe "id" do it "should have an id as an integer" do State.new.id.should be_a_kind_of(Fixnum) end - + it "should be auto-incrementing" do s1 = State.new s2 = State.new - + s2.id.should equal(s1.id + 1) end - + it "should be 1 after reset_counter! is called" do State.reset_counter! s1 = State.new s1.id.should equal(1) end end end end end diff --git a/spec/hopcoft/machine/table_converter_spec.rb b/spec/hopcoft/machine/table_converter_spec.rb index 1a1c5fc..cb2e5d9 100644 --- a/spec/hopcoft/machine/table_converter_spec.rb +++ b/spec/hopcoft/machine/table_converter_spec.rb @@ -1,133 +1,133 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe TableConverter do before do @hash = Dictionary.new @converter = TableConverter.new(@hash) end describe "transition symbols" do it "should have no transitions when an empty hash" do @converter.transition_symbols.should == [] end it "should have the symbols" do @hash[:state1] = { :transition2 => [:state2] } - + @converter.transition_symbols.should == [:transition2] end it "should have many transition symbols under various states" do @hash[:state1] = { :transition1 => [] } @hash[:state2] = { :transition2 => [] } @converter.transition_symbols.should include(:transition1) @converter.transition_symbols.should include(:transition2) end it "should use all of the transition symbols per state" do @hash[:state1] = { :transition_symbol_1 => [], :transition_symbol_2 => [] } @converter.transition_symbols.should include(:transition_symbol_1) @converter.transition_symbols.should include(:transition_symbol_2) end it "should only include a transition symbol once, even if listed under multiple states" do @hash[:state1] = { :transition_symbol_1 => [] } @hash[:state2] = { :transition_symbol_1 => [] } @converter.transition_symbols.should == [:transition_symbol_1] end it "should cache the transition symbols" do @hash[:state] = { :one => [] } lambda { @hash.delete(:state) }.should_not change { @converter.transition_symbols.dup } end end describe "primary states" do it "should be empty for an empty hash" do @converter.primary_states.should == [] end it "should have a state used as an index in the hash" do @hash[:one] = {} @converter.primary_states.should == [:one] end it "should cache the primary states" do @hash[:one] = {:two => [:three]} lambda { @hash.delete(:one) }.should_not change { @converter.primary_states.dup } end end describe "header" do it "should have an empty string with an empty hash" do @converter.header.should == [""] end it "should use the transition symbols, preceeded by an empty string" do @hash[:one] = {:two => []} @converter.header.should == ["", :two] end it "should use multiple transition symbols" do @hash[:one] = {:trans1 => []} @hash[:two] = {:trans2 => []} @converter.header.should == ["", :trans1, :trans2] end end describe "body" do it "should be empty for an empty hash" do @converter.body.should == [] end it "should have a state followed by it's result" do @hash[:one] = { :transition1 => [:two] } @converter.body.should == [[:one, [:two]]] end it "should have a symbol with no values if none are present (a degenerative case)" do @hash[:one] = { :transition => [] } @converter.body.should == [[:one, []]] end it "should use empty arrays for symbols which do not exist (the empty set)" do @hash[:one] = { :t1 => [:two] } @hash[:two] = { :t2 => [:three] } @converter.body.should == [[:one, [:two], []], [:two, [], [:three]]] end it "should use multiple target states (for a NFA)" do @hash[:one] = { :t1 => [:two, :three]} @converter.body.should == [[:one, [:two, :three]]] end end describe "to_a" do it "should be empty with an empty hash" do @converter.to_a.should == [] end it "should use the header and body" do @hash[:one] = { :two => [:three] } @converter.to_a.should == [["", :two], [[:one, [:three]]]] end end end end end diff --git a/spec/hopcoft/machine/table_displayer_spec.rb b/spec/hopcoft/machine/table_displayer_spec.rb index 5726176..aca073d 100644 --- a/spec/hopcoft/machine/table_displayer_spec.rb +++ b/spec/hopcoft/machine/table_displayer_spec.rb @@ -1,117 +1,117 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe TableDisplayer do before do @hash = Dictionary.new @displayer = TableDisplayer.new(@hash) end describe "converted table" do it "should convert symbols to strings in the header" do state = State.new(:start_state => false) @hash[state] = { :transition => [state] } @displayer.header.should == ["", "transition"] end it "should convert states to state names in the body" do state = State.new(:start_state => false) @hash[state] = { :transition => [state] } @displayer.body.should == [[state.name, state.name]] end it "should join multiple states with a comma (for an nfa)" do state1 = State.new(:name => "State 1", :start_state => false) state2 = State.new(:name => "State 2", :start_state => false) - + @hash[state1] = { :transition => [state1, state2] } @displayer.body.should == [["State 1", "State 1, State 2"]] end it "should display an empty string as an empty string (when there is no state transition" do state = State.new(:name => "State 1", :start_state => false) @hash[state] = { :transition => [] } - + @displayer.body.should == [["State 1", ""]] end it "should have the header + footer combined in to_a" do state = State.new(:name => "A", :start_state => false) @hash[state] = { :transition => [state] } @displayer.to_a.should == [["", "transition"], [["A", "A"]]] end it "should output a table" do state = State.new(:name => "A", :start_state => false) @hash[state] = { :transition => [state] } @displayer.to_s.should == <<-HERE +---+------------+ | | transition | +---+------------+ | A | A | +---+------------+ HERE end it "should display a -> in front of a start state in the first row" do state = State.new(:name => "A", :start_state => true) @hash[state] = { :transition => [state] } @displayer.to_a.should == [["", "transition"], [["-> A", "A"]]] end it "should use the correct name of the state" do state = State.new(:name => "B", :start_state => true) @hash[state] = { :transition => [state] } @displayer.to_a.should == [["", "transition"], [["-> B", "B"]]] end it "should display a * next to a final state in the first row" do state = State.new(:name => "A", :final => true, :start_state => false) - + @hash[state] = { :transition => [state] } @displayer.to_a.should == [["", "transition"], [["* A", "* A"]]] end it "should use the correct state name with the star" do state = State.new(:name => "B", :final => true, :start_state => false) - + @hash[state] = { :transition => [state] } @displayer.to_a.should == [["", "transition"], [["* B", "* B"]]] end it "should display a * -> <state-name> if the state is both final and a start state" do state = State.new(:name => "A", :final => true, :start_state => true) - + @hash[state] = { :transition => [state] } @displayer.to_a.should == [["", "transition"], [["* -> A", "* A"]]] end it "should display a star next to a final state in the middle of the table" do start_state = State.new(:name => "A", :final => false, :start_state => true) final_state = State.new(:name => "B", :final => true, :start_state => false) @hash[start_state] = { :transition => [final_state] } @displayer.body.should == [["-> A", "* B"]] end end end end end diff --git a/spec/hopcoft/machine/transition_table/targets_for_spec.rb b/spec/hopcoft/machine/transition_table/targets_for_spec.rb index eb6e84e..f8f19e7 100644 --- a/spec/hopcoft/machine/transition_table/targets_for_spec.rb +++ b/spec/hopcoft/machine/transition_table/targets_for_spec.rb @@ -1,115 +1,115 @@ require File.expand_path(File.dirname(__FILE__) + "/../../../spec_helper") module Hopcroft module Machine describe NfaTransitionTable do describe "new_transitions_for" do before do @table = NfaTransitionTable.new @state1 = State.new @state2 = State.new(:start_state => false) @state3 = State.new(:start_state => false) @state4 = State.new(:start_state => false) @state5 = State.new(:start_state => false) end - + it "should return a transition under a symbol" do @table.add_state_change @state1, @state2, :a - + @table.targets_for(@state1, :a).should == [@state2] end - + it "should use the correct sym" do @table.add_state_change @state1, @state2, :b - + @table.targets_for(@state1, :b).should == [@state2] end - + it "should only find states matching the sym" do @table.add_state_change @state1, @state2, :a @table.add_state_change @state1, @state3, :b - + @table.targets_for(@state1, :a).should == [@state2] end - + it "should return multiple transitions under the same sym" do @table.add_state_change @state1, @state2, :a @table.add_state_change @state1, @state3, :a - + @table.targets_for(@state1, :a).should == [@state2, @state3] end - + it "should return an empty array if it cannot find the sym" do @table.add_state_change @state1, @state2, :a - + @table.targets_for(@state1, :b).should == [] end - + it "should return an empty array if it cannot find the state" do @table.add_state_change @state1, @state2, :a - + @table.targets_for(mock('a state'), :a).should == [] end - + it "should find an epsilon transition *after* a match" do @table.add_state_change @state1, @state2, :a @table.add_state_change @state2, @state3, EpsilonTransition - + @table.targets_for(@state1, :a).should == [@state2, @state3] end - + it "should find multiple epsilon transitions" do @table.add_state_change @state1, @state2, :a @table.add_state_change @state2, @state3, EpsilonTransition @table.add_state_change @state2, @state4, EpsilonTransition - + @table.targets_for(@state1, :a).should == [@state2, @state3, @state4] end - + it "should follow epsilon transitions following other epsilon transitions *after* a match" do @table.add_state_change @state1, @state2, :a @table.add_state_change @state2, @state3, EpsilonTransition @table.add_state_change @state3, @state4, EpsilonTransition - + @table.targets_for(@state1, :a).should == [@state2, @state3, @state4] end - + it "should not follow a sym after matching the sym" do @table.add_state_change @state1, @state2, :a @table.add_state_change @state2, @state3, :a - + @table.targets_for(@state1, :a).should == [@state2] end - + it "should not follow a sym after matching a sym when epsilon transitions connect the syms" do @table.add_state_change @state1, @state2, :a @table.add_state_change @state2, @state3, EpsilonTransition @table.add_state_change @state3, @state4, :a - + @table.targets_for(@state1, :a).should == [@state2, @state3] end - + it "should not find other (non-epsilon) transitions after a match" do @table.add_state_change @state1, @state2, :a @table.add_state_change @state2, @state3, :a @table.add_state_change @state2, @state3, EpsilonTransition @table.add_state_change @state3, @state4, :a - + @table.targets_for(@state1, :a).should == [@state2, @state3] end - + it "should match a char under an AnyCharTransition" do @table.add_state_change @state1, @state2, AnyCharTransition - + @table.targets_for(@state1, :a).should == [@state2] end - + it "should match any char" do @table.add_state_change @state1, @state2, AnyCharTransition - + @table.targets_for(@state1, :b).should == [@state2] end end end end end diff --git a/spec/hopcoft/machine/transition_table_spec.rb b/spec/hopcoft/machine/transition_table_spec.rb index 89c515c..ba1416e 100644 --- a/spec/hopcoft/machine/transition_table_spec.rb +++ b/spec/hopcoft/machine/transition_table_spec.rb @@ -1,23 +1,23 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe TransitionTable do before do @table = TransitionTable.new end - + it "should raise a NotImplementedError when calling add_state_change" do lambda { @table.add_state_change :from, :to, :sym }.should raise_error(NotImplementedError) end - + it "should raise a NotImplementedError when calling matches?" do lambda { @table.matches?([]) }.should raise_error(NotImplementedError) end end end -end \ No newline at end of file +end diff --git a/spec/hopcoft/regex/alternation_spec.rb b/spec/hopcoft/regex/alternation_spec.rb index 88ac750..1639db8 100644 --- a/spec/hopcoft/regex/alternation_spec.rb +++ b/spec/hopcoft/regex/alternation_spec.rb @@ -1,79 +1,79 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe Alternation do describe "to_regex_s" do it "should be a|b" do one = Char.new("a") two = Char.new("b") - + alternation = Alternation.new(one, two) alternation.to_regex_s.should == "a|b" end it "should use the correct subexpressions" do one = Char.new("x") two = Char.new("y") - + alternation = Alternation.new(one, two) alternation.to_regex_s.should == "x|y" end it "should use more than two subexpressions" do one = Char.new "a" two = Char.new "b" three = Char.new "c" alternation = Alternation.new(one, two, three) alternation.to_regex_s.should == "a|b|c" end end describe "matching a string" do it "should match a with 'a|b'" do alternation = Alternation.new(Char.new("a"), Char.new("b")) alternation.matches?("a").should be_true end it "should not match a char not present" do alternation = Alternation.new(Char.new("a"), Char.new("b")) alternation.matches?("x").should be_false end it "should match 'b' with 'a|b'" do alternation = Alternation.new(Char.new("a"), Char.new("b")) alternation.matches?("b").should be_true end it "should not match 'ab' with 'a|b'" do alternation = Alternation.new(Char.new("a"), Char.new("b")) alternation.matches?("ab").should be_false end end describe "displaying the state table" do it "should not raise an error" do lambda { alternation = Alternation.new(Char.new("a"), Char.new("b")) alternation.inspect }.should_not raise_error end it "should keep the same number of states after being called several times" do alternation = Alternation.new(Char.new("a"), Char.new("b")) table = alternation.to_machine.state_table - + lambda { 3.times do table.initial_states end }.should_not change { table.initial_states.size } end end end end end diff --git a/spec/hopcoft/regex/base_spec.rb b/spec/hopcoft/regex/base_spec.rb index 4b59092..361f154 100644 --- a/spec/hopcoft/regex/base_spec.rb +++ b/spec/hopcoft/regex/base_spec.rb @@ -1,91 +1,91 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe Base do describe "==" do it "should be false if the other does not respond_to :to_regex_s" do Regex::KleenStar.new("a").should_not == Object.new end it "should be false if the other object generates a different regex" do Regex::KleenStar.new(Char.new("a")).should_not == Regex::KleenStar.new(Char.new("b")) end it "should be true if the other generates the same regex" do Regex::KleenStar.new(Char.new("a")).should == Regex::KleenStar.new(Char.new("a")) end end describe "+" do it "should produce a concatenation of two regexs" do one = Regex::Char.new("a") two = Regex::Char.new("b") concat = one + two concat.to_regex_s.should == "ab" end it "should use the correct objects" do one = Regex::Char.new("x") two = Regex::Char.new("y") (one + two).to_regex_s.should == "xy" end end describe "|" do it "should create an alternation" do one = Regex::Char.new("a") two = Regex::Char.new("b") (one | two).to_regex_s.should == "a|b" end it "should use the correct objects" do one = Regex::Char.new("x") two = Regex::Char.new("y") (one | two).to_regex_s.should == "x|y" end end describe "to_regexp" do it "should turn the object into a regexp" do Char.new("x").to_regexp.should == /x/ end it "should use the self" do Char.new("y").to_regexp.should == /y/ end it "should have #to_regex as an alias" do c = Char.new("a") c.method(:to_regex).should == c.method(:to_regexp) end end - + describe "compile" do before do @regex = Char.new("a") end - + it "should return the state machine" do @regex.compile.should be_a_kind_of(Machine::StateMachine) end - + it "should call to_dfa" do @regex.should_receive(:to_dfa) @regex.compile end - + it "should cache the dfa" do @regex.should_receive(:to_dfa).once.and_return(mock('state machine')) - + @regex.compile @regex.compile end end end end end diff --git a/spec/hopcoft/regex/char_spec.rb b/spec/hopcoft/regex/char_spec.rb index 9be86ef..4e7f382 100644 --- a/spec/hopcoft/regex/char_spec.rb +++ b/spec/hopcoft/regex/char_spec.rb @@ -1,88 +1,88 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe Char do it "should match one char" do c = Char.new("a") c.matches?("a").should be_true end it "should not match a different char" do c = Char.new("a") c.matches?("b").should be_false end it "should not match multiple chars" do c = Char.new("a") c.matches?("ab").should be_false end it "should not match an empty string" do c = Char.new("a") c.matches?("").should be_false end it "should raise an error if constructed with the empty string" do - lambda { + lambda { Char.new("") }.should raise_error end it "should have the char as the regex" do Char.new("a").to_regex_s.should == "a" Char.new("b").to_regex_s.should == "b" end it "should escape a ." do Char.new(".").to_regex_s.should == '\.' end it "should escape a +" do Char.new("+").to_regex_s.should == '\+' end it "should escape a ?" do Char.new("?").to_regex_s.should == '\?' end it "should escape a *" do Char.new("*").to_regex_s.should == '\*' end it "should escape a [" do Char.new("[").to_regex_s.should == '\[' end it "should escape a ]" do Char.new("]").to_regex_s.should == '\]' end end describe "to_machine" do it "should return a new machine" do char = Char.new("a") char.to_machine.should be_a_kind_of(Machine::StateMachine) end it "should construct the one char machine" do char = Char.new("a") start_state = char.to_machine.start_state start_state.transitions.size.should == 1 first_transition = start_state.transitions.first first_transition.symbol.should == :a first_transition.state.should be_a_final_state end it "should use the correct one char" do char = Char.new("b") start_state = char.to_machine.start_state start_state.transitions.size.should == 1 first_transition = start_state.transitions.first first_transition.symbol.should == :b end end end end diff --git a/spec/hopcoft/regex/charachter_class_spec.rb b/spec/hopcoft/regex/charachter_class_spec.rb index 649e84f..cf27595 100644 --- a/spec/hopcoft/regex/charachter_class_spec.rb +++ b/spec/hopcoft/regex/charachter_class_spec.rb @@ -1,104 +1,104 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe CharacterClass do describe "checking for valid expressions" do it "should not be valid with e-a" do lambda { CharacterClass.new("e-a") }.should raise_error(CharacterClass::InvalidCharacterClass) end - + it "should return a Char if one char long" do char = CharacterClass.new("a") char.should be_a_kind_of(Regex::Char) char.to_regex_s.should == "a" end it "should return a char if two chars long, and the first char is an escape" do char = CharacterClass.new("\\a") char.should be_a_kind_of(Regex::Char) end - + it "should be valid with a-e" do klass = CharacterClass.new("a-e") klass.to_regex_s.should == "[a-e]" end - + it "should be invalid if the second char comes before the first in the alphabet" do lambda { CharacterClass.new("b-a") }.should raise_error end - + it "should allow multiple sets of ranges" do lambda { CharacterClass.new("a-zA-Z") }.should_not raise_error end it "should have the regex string" do CharacterClass.new("a-c").to_regex_s.should == "[a-c]" end - + it "should be valid with multiple ranges" do CharacterClass.new("a-c", "e-f").to_regex_s.should == "[a-ce-f]" end - + it "should allow a range and a single char" do CharacterClass.new("a-c", "d").to_regex_s.should == "[a-cd]" end end describe "matching" do it "should match an a in [a-z]" do klass = CharacterClass.new("a-z") klass.matches?("a").should be_true end it "should match b in [a-z]" do klass = CharacterClass.new("a-z") klass.matches?("b").should be_true end it "should match an X in [A-Z]" do klass = CharacterClass.new("A-Z") klass.matches?("X").should be_true end it "should not match an a in [A-Z]" do klass = CharacterClass.new("A-Z") klass.matches?("a").should be_false end it "should match a number in [0-9]" do klass = CharacterClass.new("0-9") klass.matches?("0").should be_true end it "should match in a multi-range expression [0-9a-eA-E]" do klass = CharacterClass.new("0-9", "a-e", "A-E") klass.should be_matched_by("0") klass.should be_matched_by("1") klass.should be_matched_by("9") klass.should be_matched_by("a") klass.should be_matched_by("e") klass.should be_matched_by("A") klass.should be_matched_by("E") klass.should_not be_matched_by("f") klass.should_not be_matched_by("X") end - + it "should match when given a range and a single char" do klass = CharacterClass.new("0-9", "a") klass.should be_matched_by("0") klass.should be_matched_by("9") klass.should be_matched_by("a") klass.should_not be_matched_by("b") end end end end end diff --git a/spec/hopcoft/regex/concatenation_spec.rb b/spec/hopcoft/regex/concatenation_spec.rb index 5e6f65c..073ff65 100644 --- a/spec/hopcoft/regex/concatenation_spec.rb +++ b/spec/hopcoft/regex/concatenation_spec.rb @@ -1,46 +1,46 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe Concatenation do it "should initialize with a series of args" do one, two = mock, mock concat = Concatenation.new one, two concat.to_a.should == [one, two] end describe "to_regex_s" do it "should return the regex of the two objs" do one = mock :to_regex_s => "foo" two = mock :to_regex_s => "bar" Concatenation.new(one, two).to_regex_s.should == "foobar" end it "should use the correct regexs" do one = mock :to_regex_s => "a" two = mock :to_regex_s => "b" Concatenation.new(one, two).to_regex_s.should == "ab" end end describe "matches?" do it "should match a single char" do concat = Concatenation.new(Char.new("a")) concat.matches?("a").should be_true end it "should match a regex of the two regexs put together" do one = Char.new("a") two = Char.new("b") - + concat = Concatenation.new(one, two) - + concat.matches?("ab").should be_true end end end end end diff --git a/spec/hopcoft/regex/kleen_star_spec.rb b/spec/hopcoft/regex/kleen_star_spec.rb index c43de79..96215c7 100644 --- a/spec/hopcoft/regex/kleen_star_spec.rb +++ b/spec/hopcoft/regex/kleen_star_spec.rb @@ -1,79 +1,79 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe KleenStar do it "should take a regex" do s = KleenStar.new(Char.new("f")) s.expression.should == Char.new("f") end describe "matching" do def new_kleen_star_with_string(str) KleenStar.new(Char.new(str)) end it "should match 0 chars" do s = new_kleen_star_with_string("a") s.matches?("").should be_true end it "should match one char" do s = new_kleen_star_with_string("a") s.matches?("a").should be_true end - + it "should NOT match a different char" do s = new_kleen_star_with_string("a") s.matches?("b").should be_false end - + it "should match many of the same chars" do s = new_kleen_star_with_string("a") s.matches?("aa").should be_true end - + it "should match 10 chars" do s = new_kleen_star_with_string("a") s.matches?("aaaaaaaaaa").should be_true end it "should match 'aaaa' with '(a|b)*'" do expr = Alternation.new(Char.new("a"), Char.new("b")) s = KleenStar.new(expr) s.matches?("aaaa").should be_true end it "should match 'bbbb' with '(a|b)*'" do expr = Alternation.new(Char.new("a"), Char.new("b")) s = KleenStar.new(expr) s.matches?("bbbb").should be_true end end - + it "should have the regex string" do KleenStar.new(Char.new("a")).to_regex_s.should == "a*" end it "should be able to output the state table" do star = KleenStar.new(Char.new("a")) - + lambda { star.to_machine.state_table.inspect }.should_not raise_error end describe "==" do it "should be true with subexpressions" do one = KleenStar.new(CharacterClass.new("a-z")) two = KleenStar.new(CharacterClass.new("a-z")) one.should == two two.should == one end end end end end diff --git a/spec/hopcoft/regex/optional_symbol_spec.rb b/spec/hopcoft/regex/optional_symbol_spec.rb index 986cfab..9e715e5 100644 --- a/spec/hopcoft/regex/optional_symbol_spec.rb +++ b/spec/hopcoft/regex/optional_symbol_spec.rb @@ -1,51 +1,51 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe OptionalSymbol do def new_optional_symbol(str) OptionalSymbol.new(Char.new(str)) end - + it "should have the expression" do optional = new_optional_symbol("a") optional.expression.should == Char.new("a") end it "should have the regex" do optional = new_optional_symbol("a") optional.to_regex_s.should == "a?" end it "should use the correct expression in to_regex_s" do optional = new_optional_symbol("b") optional.to_regex_s.should == "b?" end it "should match the char if present" do optional = new_optional_symbol("a") optional.matches?("a").should be_true end it "should match an empty string" do optional = new_optional_symbol("a") optional.matches?("").should be_true end it "should not match a one char input when the char does not match" do optional = new_optional_symbol("a") optional.matches?("b").should be_false end it "should not match a two char input" do optional = new_optional_symbol("a") optional.matches?("ab").should be_false end - + it "should match the correct char" do optional = new_optional_symbol("b") optional.matches?("b").should be_true end end end end diff --git a/spec/hopcoft/regex/parser_spec.rb b/spec/hopcoft/regex/parser_spec.rb index cebe9c2..ed952e5 100644 --- a/spec/hopcoft/regex/parser_spec.rb +++ b/spec/hopcoft/regex/parser_spec.rb @@ -1,322 +1,322 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe Parser do it "should parse 'a' as a Char" do Parser.parse("a", true).should == Char.new('a') end - + it "should parse '(a)' as a Char" do Parser.parse("(a)").should == Char.new("a") end - + it "should parse 'b' as a Char" do Parser.parse("b").should == Char.new("b") end - + it "should parse 'A' as a Char" do Parser.parse("A").should == Char.new("A") end - + it "should parse 'Z' as a Char" do Parser.parse("Z").should == Char.new("Z") end - + it "should parse '0' as a Char" do Parser.parse("0").should == Char.new("0") end - + it "should parse '9' as a Char" do Parser.parse("9").should == Char.new("9") end - + it "should parse 'ab' as two chars" do result = Parser.parse("ab") result.should == (Char.new("a") + Char.new("b")) result.should be_a_kind_of(Concatenation) end - + it "should parse 'bc' as two chars" do result = Parser.parse("bc") result.should == (Char.new("b") + Char.new("c")) result.should be_a_kind_of(Concatenation) end - + it "should parse a '.' as a Dot" do Parser.parse(".").should == Dot.new end - + it "should parse a '\.' as a char dot" do Parser.parse('\.').should == Char.new(".") end - + it "should parse '\..' as an escaped char + a dot" do Parser.parse("\\..").should == (Char.new(".") + Dot.new) end - + it "should parse 'a*' as a kleen star" do Parser.parse("a*").should == KleenStar.new(Char.new("a")) end - + it "should parse 'b*' as a kleen star" do Parser.parse("b*").should == KleenStar.new(Char.new("b")) end - + it "should parse '\*' as the star char" do Parser.parse("\\*").should == Char.new("*") end - + it "should parse 'a\*' as a followed by a char" do Parser.parse("a\\*").should == (Char.new("a") + Char.new("*")) end - + it "should parse a? as an optional a" do Parser.parse("a?").should == OptionalSymbol.new(Char.new("a")) end - + it "should parse b? as an optional b" do Parser.parse("b?").should == OptionalSymbol.new(Char.new("b")) end - + it "should parse an escaped question mark as a char" do Parser.parse("\\?").should == Char.new("?") end - + it "should parse a plus" do Parser.parse("a+").should == Plus.new(Char.new("a")) end - + it "should parse 'b+'" do Parser.parse("b+").should == Plus.new(Char.new("b")) end - + it "should parse an escaped plus" do Parser.parse("\\+").should == Char.new("+") end - + it "should parse [a-z] as a character class" do Parser.parse("[a-z]").should == CharacterClass.new("a-z") end - + it "should parse [b-c] as a character class" do Parser.parse("[b-c]").should == CharacterClass.new("b-c") end - + it "should parse \ as an open bracket char" do Parser.parse("\\[").should == Char.new("[") end - + it "should parse \] as a closed bracket char" do Parser.parse("\\]").should == Char.new("]") end - + it "should parse 'ab' as a concatenation of a and b" do char1 = Char.new("a") char2 = Char.new("b") - + Parser.parse("ab").should == Concatenation.new(char1, char2) Parser.parse("ab").should be_a_kind_of(Concatenation) end - + it "should parse [a-z]* as a kleen star of a char class" do Parser.parse("[a-z]*").should == KleenStar.new(CharacterClass.new("a-z")) end - + it "should parse alternation" do result = Parser.parse("a|b") result.should be_a_kind_of(Alternation) result.should == Alternation.new(Char.new("a"), Char.new("b")) end - + it "should parse correct chars in the alternation" do result = Parser.parse("x|y") result.should be_a_kind_of(Alternation) result.should == Alternation.new(Char.new("x"), Char.new("y")) end - + it "should parse '.|a' as an alternation" do result = Parser.parse(".|a") result.should be_a_kind_of(Alternation) result.should == Alternation.new(Dot.new, Char.new("a")) end - + it "should allow a char class in the second position" do result = Parser.parse(".|[a-z]") result.should be_a_kind_of(Alternation) result.should == Alternation.new(Dot.new, CharacterClass.new("a-z")) result.expressions.last.should be_a_kind_of(CharacterClass) end - + it "should allow a plus after a char class" do result = Parser.parse("[a-z]+") result.should be_a_kind_of(Plus) result.should == Plus.new(CharacterClass.new("a-z")) end - + it "should see an escaped plus as a char" do Parser.parse('\+').should be_a_kind_of(Char) end - + it "should see an escaped plus with a argment in front of it as an escaped plus with a concatenation" do result = Parser.parse('a\+') result.should == Concatenation.new(Char.new("a"), Char.new("+")) end - + it "should allow an optional char class" do result = Parser.parse("[a-z]?") result.should == OptionalSymbol.new(CharacterClass.new("a-z")) end - + it "should parse with parens" do result = Parser.parse("([a-z])") result.should be_a_kind_of(CharacterClass) end - + it "should parse an escaped paren inside parens" do result = Parser.parse('(\()') result.should == Char.new("(") end - + it "should allow parens around a concatenation" do result = Parser.parse("(ab)") result.should == (Char.new("a") + Char.new("b")) end - + it "should parse matching escaped parens inside a set of parens" do result = Parser.parse '(\(\))' result.should == (Char.new("(") + Char.new(")")) end - + it "should parse two sets of parens around each other" do result = Parser.parse "((ab))" result.should == (Char.new("a") + Char.new("b")) end - + it "should parse a number" do result = Parser.parse("9") result.should == Char.new("9") end - + it "should parse any single non-special char (one that isn't in the regex set)" do result = Parser.parse("$") result.should == Char.new("$") end - + it "should parse an escaped or" do result = Parser.parse('\|') result.should == Char.new("|") end - + it "should parse an underscore" do result = Parser.parse("_") result.should == Char.new("_") end - + it "should parse a char class with one element" do result = Parser.parse("[a]") result.should == Char.new("a") end - + it "should parse a char class with one element but a different char" do result = Parser.parse("[b]") result.should == Char.new("b") end - + it "should parse an escaped special char inside a character class" do result = Parser.parse('[\+]') result.should be_a_kind_of(Char) result.should == Char.new("+") end - + it "should parse two escaped chars within a char range" do result = Parser.parse '[\a-\b]' result.should be_a_kind_of(CharacterClass) result.should == CharacterClass.new("\\a-\\b") end - + it "should NOT parse an empty char class" do lambda { Parser.parse("[]") }.should raise_error(Parser::ParseError) end - + ["+", "?", "*", "[", "]", "\\", "|"].each do |char| it "should not parse the regex '#{char}'" do lambda { Parser.parse("#{char}") }.should raise_error(Parser::ParseError) end end - + it "should raise an error if it cannot parse a string" do lambda { Parser.parse("[") }.should raise_error(Parser::ParseError, "could not parse the regex '['") end - + it "should use the correct string name" do lambda { Parser.parse("]") }.should raise_error(Parser::ParseError, "could not parse the regex ']'") end - + it "should allow multiple expressions inside a char class (i.e [a-zA-Z])" do result = Parser.parse("[a-zA-Z]") result.should be_a_kind_of(CharacterClass) end - + it "should be able to parse multiple ORs (a|b|c)" do result = Parser.parse("a|b|c") result.should == Alternation.new(Char.new("a"), Alternation.new(Char.new("b"), Char.new("c"))) end - + it "should be able to parse (a|b)+" do result = Parser.parse("(a|b)+") result.should be_a_kind_of(Plus) end - + it "should be able to parse (a|b+)x" do result = Parser.parse("(a|b+)x") result.should be_a_kind_of(Concatenation) end - + it "should be able to parse (a|b)+x" do result = Parser.parse("(a|b)+x") result.should be_a_kind_of(Concatenation) end - + it "should be able to parse (a)" do result = Parser.parse("(a)") result.should be_a_kind_of(Char) end - + it "should be able to parse 'a+b+'" do result = Parser.parse("a+b+", true) result.should be_a_kind_of(Concatenation) end it "should be able to parse 'a+b+c+'" do result = Parser.parse("a+b+c+") result.should be_a_kind_of(Concatenation) end it "should parse an eval 'a+b+c+" do result = Parser.parse("a+b+c+") result.should == (Plus.new(Char.new("a")) + Plus.new(Char.new("b")) + Plus.new(Char.new("c"))) end describe "debugging info" do it "should have debugging info off by default" do Parser.new.should_not be_debugging end - + it "should be able to set debugging information" do p = Parser.new p.debug = true p.should be_debugging end end end end end diff --git a/spec/hopcoft/regex/plus_spec.rb b/spec/hopcoft/regex/plus_spec.rb index b1e467e..26d6d53 100644 --- a/spec/hopcoft/regex/plus_spec.rb +++ b/spec/hopcoft/regex/plus_spec.rb @@ -1,47 +1,47 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe Plus do it "should take a regex" do s = Plus.new(Char.new("f")) s.expression.should == Char.new("f") end - + describe "matching" do def plus_with_char(str) Plus.new(Char.new(str)) end - + it "should not match an empty string" do s = plus_with_char("a") s.matches?("").should be_false end - + it "should match one char" do s = plus_with_char("a") s.matches?("a").should be_true end - + it "should not match a different char" do s = plus_with_char("a") s.matches?("b").should be_false end - + it "should match many of the same chars" do s = plus_with_char("a") s.matches?("aa").should be_true end - + it "should not match when any of the chars are different" do s = plus_with_char("a") s.matches?("aab").should be_false end end - + it "should have the regex string" do Plus.new(Char.new("a")).to_regex_s.should == "a+" end end end end diff --git a/spec/hopcoft/regex_spec.rb b/spec/hopcoft/regex_spec.rb index d3895e7..a16afea 100644 --- a/spec/hopcoft/regex_spec.rb +++ b/spec/hopcoft/regex_spec.rb @@ -1,26 +1,26 @@ require File.expand_path(File.dirname(__FILE__) + "/../spec_helper") module Hopcroft describe Regex do describe "compiling" do before do @a_regex = Regex::Char.new("a") Regex::Parser.stub!(:parse).with("a|regex").and_return @a_regex end - + it "should parse the regex" do Regex::Parser.should_receive(:parse).with("a|regex").and_return @a_regex Regex.compile("a|regex") end - + it "should compile the regex" do @a_regex.should_receive(:compile) Regex.compile("a|regex") end - + it "should return the regex" do Regex.compile("a|regex").should == @a_regex end end end -end \ No newline at end of file +end diff --git a/spec/spec.opts b/spec/spec.opts index 55716ef..e0bae3d 100644 --- a/spec/spec.opts +++ b/spec/spec.opts @@ -1,3 +1,3 @@ --color --debugger ---format profile \ No newline at end of file +--format profile diff --git a/tasks/flog.rake b/tasks/flog.rake index e31fd7d..b7d46a8 100644 --- a/tasks/flog.rake +++ b/tasks/flog.rake @@ -1,10 +1,10 @@ desc "Feel the pain of my code, and submit a refactoring patch" task :flog do puts %x(find lib | grep ".rb$" | xargs flog) end task :flog_to_disk => :create_doc_directory do puts "Flogging..." %x(find lib | grep ".rb$" | xargs flog > doc/flog.txt) puts "Done Flogging...\n" -end \ No newline at end of file +end diff --git a/tasks/sloc.rake b/tasks/sloc.rake index fb7f16a..021471c 100644 --- a/tasks/sloc.rake +++ b/tasks/sloc.rake @@ -1,16 +1,16 @@ def sloc `sloccount #{File.dirname(__FILE__)}/../lib #{File.dirname(__FILE__)}/../ext` end desc "Output sloccount report. You'll need sloccount installed." task :sloc do puts "Counting lines of code" puts sloc end desc "Write sloccount report" task :output_sloc => :create_doc_directory do File.open(File.dirname(__FILE__) + "/doc/lines_of_code.txt", "w") do |f| f << sloc end -end \ No newline at end of file +end diff --git a/tasks/tags.rake b/tasks/tags.rake index 54c0315..78952ad 100644 --- a/tasks/tags.rake +++ b/tasks/tags.rake @@ -1,23 +1,23 @@ # Build the TAGS file for Emacs -# Taken with slight modifications from +# Taken with slight modifications from # http://blog.lathi.net/articles/2007/11/07/navigating-your-projects-in-emacs # # Thanks Jim Weirich module Emacs module Tags def self.ruby_files @ruby_files ||= FileList['**/*.rb'].exclude("pkg") end end end namespace :tags do task :emacs do puts "Making Emacs TAGS file" sh "ctags -e #{Emacs::Tags.ruby_files}", :verbose => false end end desc "Build the emacs tags file" task :tags => ["tags:emacs"]
smtlaissezfaire/hopcroft
8e627c1bc18ddbdc9b628a5fe1662c8e258081cf
Remove require 'rubygems'
diff --git a/script/boot.rb b/script/boot.rb index 6fdba13..fc9ab3b 100644 --- a/script/boot.rb +++ b/script/boot.rb @@ -1,12 +1,11 @@ def load_hopcroft! - require "rubygems" reload! include Hopcroft end def reload! load "lib/hopcroft.rb" end load_hopcroft! diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 83801f2..5308c40 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,4 +1,2 @@ - -require "rubygems" require File.expand_path(File.dirname(__FILE__) + "/../lib/hopcroft") require 'facets/dictionary'
smtlaissezfaire/hopcroft
337979cf1914208584744d98162628b2505e359c
use regex compilation in the test suite
diff --git a/spec/hopcoft/integration_spec.rb b/spec/hopcoft/integration_spec.rb index 5f46fc2..b2d1b60 100644 --- a/spec/hopcoft/integration_spec.rb +++ b/spec/hopcoft/integration_spec.rb @@ -1,173 +1,173 @@ require File.expand_path(File.dirname(__FILE__) + "/../spec_helper") module Hopcroft describe "Integration tests" do describe "the regex /a/" do before do - @regex = Regex.parse("a") + @regex = Regex.compile("a") end it "should match 'a'" do @regex.should be_matched_by("a") end it "should not match 'b'" do @regex.should_not be_matched_by("b") end it "should not match 'abasdfasdf'" do @regex.should_not be_matched_by('abasdfasdf') end end describe "the regex /ab/" do before do - @regex = Regex.parse("ab") + @regex = Regex.compile("ab") end it "should match 'ab'" do @regex.should be_matched_by("ab") end it "should not match 'x'" do @regex.should_not be_matched_by("x") end it "should not match 'ba'" do @regex.should_not be_matched_by("ba") end end describe "the regex /a*/" do before do - @regex = Regex.parse("a*") + @regex = Regex.compile("a*") end it "should be matched by 'a'" do @regex.should be_matched_by("a") end it "should be matched by the empty string" do @regex.should be_matched_by("") end it "should be matched by 'aa'" do @regex.should be_matched_by("aa") end it "should be matched by 'aaa'" do @regex.should be_matched_by("aaa") end it "should not be matched by 'aab'" do @regex.should_not be_matched_by("aab") end end describe "the regex /a+/" do before do - @regex = Regex.parse("a+") + @regex = Regex.compile("a+") end it "should be matched by 'a'" do @regex.should be_matched_by("a") end it "should NOT be matched by the empty string" do @regex.should_not be_matched_by("") end it "should be matched by 'aa'" do @regex.should be_matched_by("aa") end it "should not be matched by 'aab'" do @regex.should_not be_matched_by("aab") end it "should be matched by 'aaa'" do @regex.matches?("aaa") @regex.should be_matched_by("aaa") end end describe "the regex /a|b/" do before do - @regex = Regex.parse("a|b") + @regex = Regex.compile("a|b") end it "should be matched by an 'a'" do @regex.should be_matched_by("a") end it "should be matched by a 'b'" do @regex.should be_matched_by("b") end it "should not be matched by a 'c'" do @regex.should_not be_matched_by("c") end it "should not be matched with the string 'ab'" do @regex.matched_by?("ab") @regex.should_not be_matched_by("ab") end end describe "the regex /(a|b)+/" do before do - @regex = Regex.parse("(a|b)+") + @regex = Regex.compile("(a|b)+") end it "should not match the empty string" do @regex.should_not be_matched_by("") end it "should match an a" do @regex.should be_matched_by("a") end it "should match 'b'" do @regex.should be_matched_by("b") end it "should match 'aaa'" do @regex.should be_matched_by("aaa") end it "should match 'bbb'" do @regex.should be_matched_by("bbb") end it "should match 'ababababbbaaa'" do @regex.should be_matched_by('ababababbbaaa') end it "should not be matched if it contains a different char" do @regex.should_not be_matched_by("ababbbbaacaab") end end describe "the regex (a|b)+x" do before do - @regex = Regex.parse("(a|b)+x") + @regex = Regex.compile("(a|b)+x") end it "should match 'ax'" do @regex.should be_matched_by("ax") end it "should match 'bx'" do @regex.should be_matched_by("bx") end it "should match 'ababx'" do @regex.should be_matched_by("ababx") end it "should not match 'x'" do @regex.should_not be_matched_by("x") end end end end
smtlaissezfaire/hopcroft
c2fc1aa03007bed3036038c1feaaab3ee2eec124
Override to_nfa, not to_machine on subclasses of Regex::Base. Don't alias_method - call to_nfa on Base class so that overriding to_nfa/to_machine works consistently.
diff --git a/lib/hopcroft/regex/base.rb b/lib/hopcroft/regex/base.rb index cc3aa01..e0acb12 100644 --- a/lib/hopcroft/regex/base.rb +++ b/lib/hopcroft/regex/base.rb @@ -1,60 +1,62 @@ module Hopcroft module Regex class Base def initialize(expr) @expression = expr end attr_reader :expression def ==(other) other.respond_to?(:to_regex_s) && to_regex_s == other.to_regex_s end def matches?(str) to_machine.matches? str end alias_method :matched_by?, :matches? def +(other) Concatenation.new(self, other) end def |(other) Alternation.new(self, other) end def to_regexp Regexp.new(to_regex_s) end alias_method :to_regex, :to_regexp def to_nfa new_machine do |m, start_state| build_machine(start_state) end end def to_dfa to_nfa.to_dfa end - alias_method :to_machine, :to_dfa + def to_machine + to_nfa + end def compile @dfa ||= to_dfa end private def new_machine returning Machine::StateMachine.new do |machine| yield machine, machine.start_state if block_given? end end end end end diff --git a/lib/hopcroft/regex/concatenation.rb b/lib/hopcroft/regex/concatenation.rb index 2e2695f..5f8f2be 100644 --- a/lib/hopcroft/regex/concatenation.rb +++ b/lib/hopcroft/regex/concatenation.rb @@ -1,38 +1,38 @@ require 'enumerator' module Hopcroft module Regex class Concatenation < Base def initialize(*objs) @array = objs end def to_regex_s @array.map { |a| a.to_regex_s }.join("") end def to_a @array end - def to_machine + def to_nfa machines = components.dup machines.each_cons(2) do |first, second| first.final_states.each do |state| state.add_transition :machine => second state.final_state = false end end machines.first end private def components @array.map { |a| a.to_machine } end end end end
smtlaissezfaire/hopcroft
593eda0f9e56a94575d00dcf4fce54decc83f053
Add regex compilation
diff --git a/lib/hopcroft/regex.rb b/lib/hopcroft/regex.rb index 725a7e1..2f7fc1c 100644 --- a/lib/hopcroft/regex.rb +++ b/lib/hopcroft/regex.rb @@ -1,34 +1,40 @@ require "treetop" module Hopcroft module Regex SPECIAL_CHARS = [ DOT = ".", PLUS = "+", QUESTION = "?", STAR = "*", OPEN_BRACKET = "[", CLOSE_BRACKET = "]", ESCAPE_CHAR = "\\", ALTERNATION = "|" ] extend Using using :Base using :Char using :KleenStar using :Plus using :Dot using :CharacterClass using :OptionalSymbol using :Concatenation using :Alternation using :SyntaxNodes using :Parser def self.parse(from_string) Parser.parse(from_string) end + + def self.compile(string) + returning parse(string) do |regex| + regex.compile + end + end end end diff --git a/lib/hopcroft/regex/base.rb b/lib/hopcroft/regex/base.rb index 35b4ef2..cc3aa01 100644 --- a/lib/hopcroft/regex/base.rb +++ b/lib/hopcroft/regex/base.rb @@ -1,56 +1,60 @@ module Hopcroft module Regex class Base def initialize(expr) @expression = expr end attr_reader :expression def ==(other) other.respond_to?(:to_regex_s) && to_regex_s == other.to_regex_s end def matches?(str) to_machine.matches? str end alias_method :matched_by?, :matches? def +(other) Concatenation.new(self, other) end def |(other) Alternation.new(self, other) end def to_regexp Regexp.new(to_regex_s) end alias_method :to_regex, :to_regexp def to_nfa new_machine do |m, start_state| build_machine(start_state) end end def to_dfa to_nfa.to_dfa end alias_method :to_machine, :to_dfa + + def compile + @dfa ||= to_dfa + end private def new_machine returning Machine::StateMachine.new do |machine| yield machine, machine.start_state if block_given? end end end end end diff --git a/spec/hopcoft/regex/base_spec.rb b/spec/hopcoft/regex/base_spec.rb index e793265..4b59092 100644 --- a/spec/hopcoft/regex/base_spec.rb +++ b/spec/hopcoft/regex/base_spec.rb @@ -1,69 +1,91 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Regex describe Base do describe "==" do it "should be false if the other does not respond_to :to_regex_s" do Regex::KleenStar.new("a").should_not == Object.new end it "should be false if the other object generates a different regex" do Regex::KleenStar.new(Char.new("a")).should_not == Regex::KleenStar.new(Char.new("b")) end it "should be true if the other generates the same regex" do Regex::KleenStar.new(Char.new("a")).should == Regex::KleenStar.new(Char.new("a")) end end describe "+" do it "should produce a concatenation of two regexs" do one = Regex::Char.new("a") two = Regex::Char.new("b") concat = one + two concat.to_regex_s.should == "ab" end it "should use the correct objects" do one = Regex::Char.new("x") two = Regex::Char.new("y") (one + two).to_regex_s.should == "xy" end end describe "|" do it "should create an alternation" do one = Regex::Char.new("a") two = Regex::Char.new("b") (one | two).to_regex_s.should == "a|b" end it "should use the correct objects" do one = Regex::Char.new("x") two = Regex::Char.new("y") (one | two).to_regex_s.should == "x|y" end end describe "to_regexp" do it "should turn the object into a regexp" do Char.new("x").to_regexp.should == /x/ end it "should use the self" do Char.new("y").to_regexp.should == /y/ end it "should have #to_regex as an alias" do c = Char.new("a") c.method(:to_regex).should == c.method(:to_regexp) end end + + describe "compile" do + before do + @regex = Char.new("a") + end + + it "should return the state machine" do + @regex.compile.should be_a_kind_of(Machine::StateMachine) + end + + it "should call to_dfa" do + @regex.should_receive(:to_dfa) + @regex.compile + end + + it "should cache the dfa" do + @regex.should_receive(:to_dfa).once.and_return(mock('state machine')) + + @regex.compile + @regex.compile + end + end end end end diff --git a/spec/hopcoft/regex_spec.rb b/spec/hopcoft/regex_spec.rb new file mode 100644 index 0000000..d3895e7 --- /dev/null +++ b/spec/hopcoft/regex_spec.rb @@ -0,0 +1,26 @@ +require File.expand_path(File.dirname(__FILE__) + "/../spec_helper") + +module Hopcroft + describe Regex do + describe "compiling" do + before do + @a_regex = Regex::Char.new("a") + Regex::Parser.stub!(:parse).with("a|regex").and_return @a_regex + end + + it "should parse the regex" do + Regex::Parser.should_receive(:parse).with("a|regex").and_return @a_regex + Regex.compile("a|regex") + end + + it "should compile the regex" do + @a_regex.should_receive(:compile) + Regex.compile("a|regex") + end + + it "should return the regex" do + Regex.compile("a|regex").should == @a_regex + end + end + end +end \ No newline at end of file
smtlaissezfaire/hopcroft
ab0f66c0a135208b0d421f6ca08e5f0467753df8
Add --format profile to spec.opts
diff --git a/spec/spec.opts b/spec/spec.opts index 342faa2..55716ef 100644 --- a/spec/spec.opts +++ b/spec/spec.opts @@ -1,2 +1,3 @@ --color ---debugger \ No newline at end of file +--debugger +--format profile \ No newline at end of file
smtlaissezfaire/hopcroft
7b1b1f2341507d7d75c485411660b4169b4bf504
Speed up test suite time (and nfa->dfa conversion time) by caching the symbols in the nfa.
diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index 0a27dec..d6bc380 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,81 +1,81 @@ module Hopcroft module Converters class NfaToDfaConverter include Machine::StateMachineHelpers def initialize(nfa) @nfa = nfa @nfa_states = {} end attr_reader :nfa def convert start_state = [@nfa.start_state] @nfa_states = { start_state => false } returning Machine::StateMachine.new do |dfa| dfa.start_state = dfa_state_for(start_state) while nfa_state = unmarked_states.first mark_state(nfa_state) symbols.each do |sym| target_nfa_states = move(epsilon_closure(nfa_state), sym) if target_nfa_states.any? add_nfa_state(target_nfa_states) source = dfa_state_for(nfa_state) target = dfa_state_for(target_nfa_states) source.add_transition :symbol => sym, :state => target end end end end end private def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end def mark_state(nfa_state) @nfa_states[nfa_state] = true end def symbols - @nfa.symbols + @symbols ||= @nfa.symbols end def move(nfa_states, symbol) to_collection(nfa_states).target_states(symbol) end def to_collection(nfa_states) if nfa_states.respond_to? :target_states nfa_states else NfaStateCollection.new(nfa_states) end end def dfa_state_for(nfa_states) to_collection(nfa_states).dfa_state end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
d6af05bd08c87be55f44bb2ecee617549ac94410
Refactoring
diff --git a/lib/hopcroft/converters.rb b/lib/hopcroft/converters.rb index 3a9a05d..ce4b029 100644 --- a/lib/hopcroft/converters.rb +++ b/lib/hopcroft/converters.rb @@ -1,7 +1,8 @@ module Hopcroft module Converters extend Using + using :NfaStateCollection using :NfaToDfaConverter end end \ No newline at end of file diff --git a/lib/hopcroft/converters/nfa_state_collection.rb b/lib/hopcroft/converters/nfa_state_collection.rb new file mode 100644 index 0000000..2e473a8 --- /dev/null +++ b/lib/hopcroft/converters/nfa_state_collection.rb @@ -0,0 +1,73 @@ +module Hopcroft + module Converters + class NfaStateCollection < Array + class << self + def nfa_to_dfa_states + @nfa_to_dfa_states ||= {} + end + + def register(obj, state) + nfa_to_dfa_states[obj] ||= state + end + end + + def dfa_state + @dfa_state ||= find_or_create_dfa_state + end + + def find_or_create_dfa_state + find_dfa_state || create_dfa_state + end + + def find_dfa_state + self.class.nfa_to_dfa_states[self] + end + + def create_dfa_state + returning new_dfa_state do |state| + register(state) + end + end + + def new_dfa_state + returning Machine::State.new do |state| + state.start_state = has_start_state? + state.final_state = has_final_state? + end + end + + def target_states(symbol) + target_transitions = [] + + each do |state| + additional_transitions = state.transitions.select { |t| t.symbol == symbol } + target_transitions.concat(additional_transitions) + end + + target_transitions.map { |t| t.state } + end + + def has_start_state? + any? { |s| s.start_state? } + end + + def has_final_state? + any? { |s| s.final_state? } + end + + def sort + sort_by { |state| state.id } + end + + def ==(other) + sort == other.sort + end + + private + + def register(state) + self.class.register(self, state) + end + end + end +end \ No newline at end of file diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index e9328c3..0a27dec 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,110 +1,81 @@ module Hopcroft module Converters class NfaToDfaConverter include Machine::StateMachineHelpers def initialize(nfa) @nfa = nfa @nfa_states = {} - @nfa_to_dfa_states = {} end attr_reader :nfa def convert start_state = [@nfa.start_state] @nfa_states = { start_state => false } - returning new_machine do |dfa| - dfa.start_state = find_or_create_state(start_state) + returning Machine::StateMachine.new do |dfa| + dfa.start_state = dfa_state_for(start_state) while nfa_state = unmarked_states.first mark_state(nfa_state) symbols.each do |sym| target_nfa_states = move(epsilon_closure(nfa_state), sym) if target_nfa_states.any? add_nfa_state(target_nfa_states) - source = find_or_create_state(nfa_state) - target = find_or_create_state(target_nfa_states) + source = dfa_state_for(nfa_state) + target = dfa_state_for(target_nfa_states) source.add_transition :symbol => sym, :state => target end end end end end private def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end def mark_state(nfa_state) @nfa_states[nfa_state] = true end def symbols @nfa.symbols end def move(nfa_states, symbol) - target_transitions = [] - - nfa_states.each do |state| - additional_transitions = state.transitions.select { |t| t.symbol == symbol } - target_transitions.concat(additional_transitions) - end - - target_transitions.map { |t| t.state } - end - - def find_or_create_state(nfa_states) - nfa_states = ordered_nfa_states(nfa_states) - find_dfa_corresponding_to_nfa_state(nfa_states) || new_dfa_state(nfa_states) - end - - def any_final?(states) - states.any? { |s| s.final_state? } + to_collection(nfa_states).target_states(symbol) end - def find_dfa_corresponding_to_nfa_state(nfa_states) - @nfa_to_dfa_states[nfa_states] - end - - def new_dfa_state(nfa_states) - returning Machine::State.new do |state| - @nfa_to_dfa_states[nfa_states] = state - state.start_state = any_start_states?(nfa_states) - state.final_state = true if any_final?(nfa_states) + def to_collection(nfa_states) + if nfa_states.respond_to? :target_states + nfa_states + else + NfaStateCollection.new(nfa_states) end end - def any_start_states?(nfa_states) - nfa_states.any? { |s| s.start_state? } - end - - def ordered_nfa_states(nfa_states) - nfa_states.sort_by { |state| state.id } - end - - def new_machine - Machine::StateMachine.new + def dfa_state_for(nfa_states) + to_collection(nfa_states).dfa_state end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
7d079c112a656e0efac5325e1f4bdc36988e4928
Set start states appropriately on NFA->DFA conversion. (This only affects the display when using the state table w/ the terminal-table gem)
diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index 0dfbc54..e9328c3 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,105 +1,110 @@ module Hopcroft module Converters class NfaToDfaConverter include Machine::StateMachineHelpers def initialize(nfa) @nfa = nfa @nfa_states = {} @nfa_to_dfa_states = {} end attr_reader :nfa def convert start_state = [@nfa.start_state] @nfa_states = { start_state => false } returning new_machine do |dfa| dfa.start_state = find_or_create_state(start_state) while nfa_state = unmarked_states.first mark_state(nfa_state) symbols.each do |sym| target_nfa_states = move(epsilon_closure(nfa_state), sym) if target_nfa_states.any? add_nfa_state(target_nfa_states) source = find_or_create_state(nfa_state) target = find_or_create_state(target_nfa_states) source.add_transition :symbol => sym, :state => target end end end end end private def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end def mark_state(nfa_state) @nfa_states[nfa_state] = true end def symbols @nfa.symbols end def move(nfa_states, symbol) target_transitions = [] nfa_states.each do |state| additional_transitions = state.transitions.select { |t| t.symbol == symbol } target_transitions.concat(additional_transitions) end target_transitions.map { |t| t.state } end def find_or_create_state(nfa_states) nfa_states = ordered_nfa_states(nfa_states) find_dfa_corresponding_to_nfa_state(nfa_states) || new_dfa_state(nfa_states) end def any_final?(states) states.any? { |s| s.final_state? } end def find_dfa_corresponding_to_nfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] end def new_dfa_state(nfa_states) returning Machine::State.new do |state| @nfa_to_dfa_states[nfa_states] = state + state.start_state = any_start_states?(nfa_states) state.final_state = true if any_final?(nfa_states) end end + def any_start_states?(nfa_states) + nfa_states.any? { |s| s.start_state? } + end + def ordered_nfa_states(nfa_states) nfa_states.sort_by { |state| state.id } end def new_machine Machine::StateMachine.new end end end end \ No newline at end of file diff --git a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb index b10147f..5a777b6 100644 --- a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb +++ b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb @@ -1,171 +1,177 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Converters describe NfaToDfaConverter do before do @nfa = Machine::StateMachine.new end it "should take an state machine" do NfaToDfaConverter.new(@nfa).nfa.should equal(@nfa) end describe "conversion" do before do @converter = NfaToDfaConverter.new(@nfa) end it "should build a new state machine" do @converter.convert.should be_a_kind_of(Machine::StateMachine) end it "should have a start state" do @converter.convert.start_state.should_not be_nil end it "should keep a machine with a start state + no other states" do @converter.convert.start_state.transitions.should == [] end describe "with a dfa: state1(start) -> state2" do it "should create a new machine a transition" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end it "should create the new machine with the symbol :foo" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:foo) end it "should use the correct symbol" do @nfa.start_state.add_transition :symbol => :bar conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:bar) end it "should not have an identical (object identical) start state" do conversion = @converter.convert @nfa.start_state.should_not equal(conversion.start_state) end it "should not have the start state as a final state" do @nfa.start_state.add_transition :symbol => :foo, :final => true conversion = @converter.convert conversion.start_state.should_not be_a_final_state end it "should have the final state as final" do @nfa.start_state.add_transition :symbol => :foo, :final => true conversion = @converter.convert conversion.start_state.transitions.first.state.should be_final end + + it "should not have the final state as a start state" do + @nfa.start_state.add_transition :symbol => :foo, :final => true + conversion = @converter.convert + conversion.start_state.transitions.first.state.should_not be_a_start_state + end end describe "a dfa with state1 -> state2 -> state3" do before do state2 = @nfa.start_state.add_transition :symbol => :foo state3 = state2.add_transition :symbol => :bar end it "should have a transition to state2" do conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end it "should have a transition to state3" do conversion = @converter.convert conversion.start_state.transitions.first.state.transitions.size.should == 1 end end describe "a dfa with a start state which loops back to itself (on a sym)" do before do start_state = @nfa.start_state start_state.add_transition :symbol => :f, :state => start_state @conversion = @converter.convert end it "should have a start state" do @conversion.start_state.should_not be_nil end it "should have one transition on the start state" do @conversion.start_state.transitions.size.should == 1 end it "should transition back to itself" do @conversion.start_state.transitions.first.state.should equal(@conversion.start_state) end end describe "an nfa with start state leading to two different states on the same symbol" do before do @nfa.start_state.add_transition :symbol => :a @nfa.start_state.add_transition :symbol => :a @conversion = @converter.convert end it "should only have one transition out of the start state" do @conversion.start_state.transitions.size.should == 1 end end describe "an NFA with an epsilon transition (start -> a -> epsilon -> b)" do before do two = @nfa.start_state.add_transition :symbol => :a three = two.add_transition :symbol => Machine::EpsilonTransition four = three.add_transition :symbol => :b @conversion = @converter.convert end it "should have one transition coming from the start state" do @conversion.start_state.number_of_transitions.should == 1 end it "should have the first transition on an a" do @conversion.start_state.transitions.first.symbol.should equal(:a) end it "should have a second transition to a b" do second_state = @conversion.start_state.transitions.first.state second_state.transitions.size.should == 1 second_state.transitions.first.symbol.should equal(:b) end end describe "with an epsilon transition on the same symbol to two different final states" do before do two = @nfa.start_state.add_transition :symbol => :a three = @nfa.start_state.add_transition :symbol => :a @conversion = @converter.convert end it "should have only one transition out of the start state" do @conversion.start_state.transitions.size.should == 1 end it "should have the transition out of the start state on the symbol" do @conversion.start_state.transitions.first.symbol.should == :a end it "should transition to a new state with no transitions" do target_state = @conversion.start_state.transitions.first.state target_state.transitions.should == [] end end end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
acd1f10b4d1ba9439b8863c4e162868930c26d40
Always set final states in nfa->dfa conversion (not only for a target). Refactor.
diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index a9b9673..0dfbc54 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,105 +1,105 @@ module Hopcroft module Converters class NfaToDfaConverter include Machine::StateMachineHelpers def initialize(nfa) @nfa = nfa @nfa_states = {} @nfa_to_dfa_states = {} end attr_reader :nfa def convert start_state = [@nfa.start_state] @nfa_states = { start_state => false } returning new_machine do |dfa| dfa.start_state = find_or_create_state(start_state) while nfa_state = unmarked_states.first mark_state(nfa_state) symbols.each do |sym| target_nfa_states = move(epsilon_closure(nfa_state), sym) if target_nfa_states.any? add_nfa_state(target_nfa_states) - find_or_create_state(nfa_state).add_transition :symbol => sym, :state => find_or_create_target_state(target_nfa_states) + + source = find_or_create_state(nfa_state) + target = find_or_create_state(target_nfa_states) + source.add_transition :symbol => sym, :state => target end end end end end private def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end def mark_state(nfa_state) @nfa_states[nfa_state] = true end def symbols @nfa.symbols end def move(nfa_states, symbol) target_transitions = [] nfa_states.each do |state| additional_transitions = state.transitions.select { |t| t.symbol == symbol } target_transitions.concat(additional_transitions) end target_transitions.map { |t| t.state } end def find_or_create_state(nfa_states) nfa_states = ordered_nfa_states(nfa_states) find_dfa_corresponding_to_nfa_state(nfa_states) || new_dfa_state(nfa_states) end - def find_or_create_target_state(nfa_states) - returning find_or_create_state(nfa_states) do |state| - state.final_state = true if any_final?(nfa_states) - end - end - def any_final?(states) states.any? { |s| s.final_state? } end def find_dfa_corresponding_to_nfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] end def new_dfa_state(nfa_states) - @nfa_to_dfa_states[nfa_states] = Machine::State.new + returning Machine::State.new do |state| + @nfa_to_dfa_states[nfa_states] = state + state.final_state = true if any_final?(nfa_states) + end end def ordered_nfa_states(nfa_states) nfa_states.sort_by { |state| state.id } end def new_machine Machine::StateMachine.new end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
368e7639dbb7c13bf6bb3336654166d4e4816b42
Add --debugger flag to spec.opts
diff --git a/spec/spec.opts b/spec/spec.opts index 5052887..342faa2 100644 --- a/spec/spec.opts +++ b/spec/spec.opts @@ -1 +1,2 @@ ---color \ No newline at end of file +--color +--debugger \ No newline at end of file
smtlaissezfaire/hopcroft
a693fac69717d7a80f542deffd70387f1912dbfb
Use dfa's, not nfa when converting a state machine to a state table
diff --git a/lib/hopcroft/regex/base.rb b/lib/hopcroft/regex/base.rb index 100babc..35b4ef2 100644 --- a/lib/hopcroft/regex/base.rb +++ b/lib/hopcroft/regex/base.rb @@ -1,52 +1,56 @@ module Hopcroft module Regex class Base def initialize(expr) @expression = expr end attr_reader :expression def ==(other) other.respond_to?(:to_regex_s) && to_regex_s == other.to_regex_s end def matches?(str) to_machine.matches? str end alias_method :matched_by?, :matches? def +(other) Concatenation.new(self, other) end def |(other) Alternation.new(self, other) end def to_regexp Regexp.new(to_regex_s) end alias_method :to_regex, :to_regexp def to_nfa new_machine do |m, start_state| build_machine(start_state) end end - alias_method :to_machine, :to_nfa + def to_dfa + to_nfa.to_dfa + end + + alias_method :to_machine, :to_dfa private def new_machine returning Machine::StateMachine.new do |machine| yield machine, machine.start_state if block_given? end end end end end
smtlaissezfaire/hopcroft
fab0d7c8f75934a6f38c760dd95e335071ac3a66
Revert "Use epsilon_closure, not [start_state]"
diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index ffefd93..a9b9673 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,105 +1,105 @@ module Hopcroft module Converters class NfaToDfaConverter include Machine::StateMachineHelpers def initialize(nfa) @nfa = nfa @nfa_states = {} @nfa_to_dfa_states = {} end attr_reader :nfa def convert - start_state = epsilon_closure(@nfa.start_state) + start_state = [@nfa.start_state] @nfa_states = { start_state => false } returning new_machine do |dfa| dfa.start_state = find_or_create_state(start_state) while nfa_state = unmarked_states.first mark_state(nfa_state) symbols.each do |sym| target_nfa_states = move(epsilon_closure(nfa_state), sym) if target_nfa_states.any? add_nfa_state(target_nfa_states) find_or_create_state(nfa_state).add_transition :symbol => sym, :state => find_or_create_target_state(target_nfa_states) end end end end end private def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end def mark_state(nfa_state) @nfa_states[nfa_state] = true end def symbols @nfa.symbols end def move(nfa_states, symbol) target_transitions = [] nfa_states.each do |state| additional_transitions = state.transitions.select { |t| t.symbol == symbol } target_transitions.concat(additional_transitions) end target_transitions.map { |t| t.state } end def find_or_create_state(nfa_states) nfa_states = ordered_nfa_states(nfa_states) find_dfa_corresponding_to_nfa_state(nfa_states) || new_dfa_state(nfa_states) end def find_or_create_target_state(nfa_states) returning find_or_create_state(nfa_states) do |state| state.final_state = true if any_final?(nfa_states) end end def any_final?(states) states.any? { |s| s.final_state? } end def find_dfa_corresponding_to_nfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] end def new_dfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] = Machine::State.new end def ordered_nfa_states(nfa_states) nfa_states.sort_by { |state| state.id } end def new_machine Machine::StateMachine.new end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
38512bed9a65a54a1a6170ea6d89154ace33ff18
use concat instead of push *
diff --git a/lib/hopcroft/machine/nfa_transition_table.rb b/lib/hopcroft/machine/nfa_transition_table.rb index d883544..73eab76 100644 --- a/lib/hopcroft/machine/nfa_transition_table.rb +++ b/lib/hopcroft/machine/nfa_transition_table.rb @@ -1,88 +1,84 @@ module Hopcroft module Machine class NfaTransitionTable < TransitionTable def start_state=(start_state) self[start_state] ||= {} super end # Create a transition without marking appropriate start states def add_state_change(from_state, to_state, transition_symbol) sym = transition_symbol self[from_state] ||= {} self[from_state][sym] ||= [] self[from_state][sym] << to_state end def has_state_change?(from_state, to_state, transition_symbol) super && self[from_state][transition_symbol].include?(to_state) end def targets_for(state, transition_sym) find_targets_matching(state, transition_sym) do |target| epsilon_states_following(target) end end def initial_states [start_state] + epsilon_states_following(start_state) end def next_transitions(states, sym) states.map { |s| targets_for(s, sym) }.compact.flatten end def matches?(input_array, current_states = initial_states) raise_if_no_start_state input_array.each do |sym| current_states = next_transitions(current_states, sym.to_sym) end current_states.any? { |state| state.final? } end def symbols values.map { |v| v.keys }.flatten.uniq.reject { |sym| sym == EpsilonTransition } end private def epsilon_states_following(state) find_targets_matching(state, EpsilonTransition) do |target| epsilon_states_following(target) end end def find_targets_matching(state, transition_sym, &recursion_block) returning Array.new do |a| direct_targets = find_targets_for(state, transition_sym) - append a, direct_targets + a.concat(direct_targets) direct_targets.each do |target| - append a, recursion_block.call(target) + a.concat(recursion_block.call(target)) end end end def find_targets_for(state, transition_sym) returning Array.new do |a| if state = self[state] if state[transition_sym] - append a, state[transition_sym] + a.concat(state[transition_sym]) end if state[AnyCharTransition] && transition_sym != EpsilonTransition - append a, state[AnyCharTransition] + a.concat(state[AnyCharTransition]) end end end end - - def append(array1, array2) - array1.push *array2 - end end end end diff --git a/lib/hopcroft/machine/state.rb b/lib/hopcroft/machine/state.rb index 2f9220c..e5e63f5 100644 --- a/lib/hopcroft/machine/state.rb +++ b/lib/hopcroft/machine/state.rb @@ -1,132 +1,132 @@ module Hopcroft module Machine class State include Identifiable def initialize(options={}) track_id @start_state = options[:start_state] if options.has_key?(:start_state) @final_state = options[:final] if options.has_key?(:final) assign_name(options) end attr_reader :name alias_method :to_s, :name def inspect "#{name} {start: #{start_state?}, final: #{final_state?}, transitions: #{transitions.size}}" end def transitions @transitions ||= [] end attr_writer :transitions def epsilon_transitions transitions.select { |t| t.epsilon_transition? } end def number_of_transitions transitions.size end # Accepts the following hash arguments: # # :machine => m (optional). Links current state to start state of machine # given with an epsilon transition. # :start_state => true | false. Make the state a start state. Defaults to false # :final => true | false. Make the state a final state. Defaults to false # :state => a_state (if none passed, a new one is constructed) # :symbol => Symbol to transition to. # :epsilon => An Epsilon Transition instead of a regular symbol transition # :any => An any symbol transition. Equivalent to a regex '.' # def add_transition(args={}) args[:start_state] = false unless args.has_key?(:start_state) if args[:machine] machine = args[:machine] args[:state] = machine.start_state args[:state].start_state = false args[:epsilon] = true else args[:state] ||= State.new(args) end returning args[:state] do |state| transitions << transition_for(args, state) yield(state) if block_given? state end end def transition_for(args, state) if args[:epsilon] EpsilonTransition.new(state) elsif args[:any] AnyCharTransition.new(state) else Transition.new(args[:symbol], state) end end def start_state? @start_state.equal?(false) ? false : true end attr_writer :start_state def final_state? @final_state ? true : false end alias_method :final?, :final_state? attr_writer :final_state def substates(excluded_states = []) returning [] do |list| follow_states.each do |state| unless excluded_states.include?(state) excluded_states << state list.push state - list.push *state.substates(excluded_states) + list.concat(state.substates(excluded_states)) end end end end def follow_states(excluded_states = []) transitions.map { |t| t.state }.reject { |s| excluded_states.include?(s) } end def add_transitions_to_table(table) transitions.each do |transition| to = transition.to unless table.has_state_change?(self, to, transition.symbol) table.add_state_change(self, to, transition.symbol) transition.to.add_transitions_to_table(table) end end end def deep_clone returning clone do |c| c.transitions = transitions.map { |t| t.deep_clone } end end private def assign_name(options) @name = options[:name] ? options[:name] : "State #{@id}" end end end end
smtlaissezfaire/hopcroft
4d353acb7ec6d1c4fe5b6ec0fb053e59385c181d
Use epsilon_closure, not [start_state]
diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index a9b9673..ffefd93 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,105 +1,105 @@ module Hopcroft module Converters class NfaToDfaConverter include Machine::StateMachineHelpers def initialize(nfa) @nfa = nfa @nfa_states = {} @nfa_to_dfa_states = {} end attr_reader :nfa def convert - start_state = [@nfa.start_state] + start_state = epsilon_closure(@nfa.start_state) @nfa_states = { start_state => false } returning new_machine do |dfa| dfa.start_state = find_or_create_state(start_state) while nfa_state = unmarked_states.first mark_state(nfa_state) symbols.each do |sym| target_nfa_states = move(epsilon_closure(nfa_state), sym) if target_nfa_states.any? add_nfa_state(target_nfa_states) find_or_create_state(nfa_state).add_transition :symbol => sym, :state => find_or_create_target_state(target_nfa_states) end end end end end private def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end def mark_state(nfa_state) @nfa_states[nfa_state] = true end def symbols @nfa.symbols end def move(nfa_states, symbol) target_transitions = [] nfa_states.each do |state| additional_transitions = state.transitions.select { |t| t.symbol == symbol } target_transitions.concat(additional_transitions) end target_transitions.map { |t| t.state } end def find_or_create_state(nfa_states) nfa_states = ordered_nfa_states(nfa_states) find_dfa_corresponding_to_nfa_state(nfa_states) || new_dfa_state(nfa_states) end def find_or_create_target_state(nfa_states) returning find_or_create_state(nfa_states) do |state| state.final_state = true if any_final?(nfa_states) end end def any_final?(states) states.any? { |s| s.final_state? } end def find_dfa_corresponding_to_nfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] end def new_dfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] = Machine::State.new end def ordered_nfa_states(nfa_states) nfa_states.sort_by { |state| state.id } end def new_machine Machine::StateMachine.new end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
a586c10584dec4a3921881109a069a6ca0378799
Make states appropriately final in NFA -> DFA conversion
diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index a33e935..a9b9673 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,95 +1,105 @@ module Hopcroft module Converters class NfaToDfaConverter include Machine::StateMachineHelpers def initialize(nfa) @nfa = nfa @nfa_states = {} @nfa_to_dfa_states = {} end attr_reader :nfa def convert start_state = [@nfa.start_state] @nfa_states = { start_state => false } returning new_machine do |dfa| dfa.start_state = find_or_create_state(start_state) while nfa_state = unmarked_states.first mark_state(nfa_state) symbols.each do |sym| target_nfa_states = move(epsilon_closure(nfa_state), sym) if target_nfa_states.any? add_nfa_state(target_nfa_states) - find_or_create_state(nfa_state).add_transition :symbol => sym, :state => find_or_create_state(target_nfa_states) + find_or_create_state(nfa_state).add_transition :symbol => sym, :state => find_or_create_target_state(target_nfa_states) end end end end end private def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end def mark_state(nfa_state) @nfa_states[nfa_state] = true end def symbols @nfa.symbols end def move(nfa_states, symbol) target_transitions = [] nfa_states.each do |state| additional_transitions = state.transitions.select { |t| t.symbol == symbol } target_transitions.concat(additional_transitions) end target_transitions.map { |t| t.state } end def find_or_create_state(nfa_states) nfa_states = ordered_nfa_states(nfa_states) find_dfa_corresponding_to_nfa_state(nfa_states) || new_dfa_state(nfa_states) end + def find_or_create_target_state(nfa_states) + returning find_or_create_state(nfa_states) do |state| + state.final_state = true if any_final?(nfa_states) + end + end + + def any_final?(states) + states.any? { |s| s.final_state? } + end + def find_dfa_corresponding_to_nfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] end def new_dfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] = Machine::State.new end def ordered_nfa_states(nfa_states) nfa_states.sort_by { |state| state.id } end def new_machine Machine::StateMachine.new end end end end \ No newline at end of file diff --git a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb index 5244d3d..b10147f 100644 --- a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb +++ b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb @@ -1,159 +1,171 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Converters describe NfaToDfaConverter do before do @nfa = Machine::StateMachine.new end it "should take an state machine" do NfaToDfaConverter.new(@nfa).nfa.should equal(@nfa) end describe "conversion" do before do @converter = NfaToDfaConverter.new(@nfa) end it "should build a new state machine" do @converter.convert.should be_a_kind_of(Machine::StateMachine) end it "should have a start state" do @converter.convert.start_state.should_not be_nil end it "should keep a machine with a start state + no other states" do @converter.convert.start_state.transitions.should == [] end describe "with a dfa: state1(start) -> state2" do it "should create a new machine a transition" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end it "should create the new machine with the symbol :foo" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:foo) end it "should use the correct symbol" do @nfa.start_state.add_transition :symbol => :bar conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:bar) end it "should not have an identical (object identical) start state" do conversion = @converter.convert @nfa.start_state.should_not equal(conversion.start_state) end + + it "should not have the start state as a final state" do + @nfa.start_state.add_transition :symbol => :foo, :final => true + conversion = @converter.convert + conversion.start_state.should_not be_a_final_state + end + + it "should have the final state as final" do + @nfa.start_state.add_transition :symbol => :foo, :final => true + conversion = @converter.convert + conversion.start_state.transitions.first.state.should be_final + end end describe "a dfa with state1 -> state2 -> state3" do before do state2 = @nfa.start_state.add_transition :symbol => :foo state3 = state2.add_transition :symbol => :bar end it "should have a transition to state2" do conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end it "should have a transition to state3" do conversion = @converter.convert conversion.start_state.transitions.first.state.transitions.size.should == 1 end end describe "a dfa with a start state which loops back to itself (on a sym)" do before do start_state = @nfa.start_state start_state.add_transition :symbol => :f, :state => start_state @conversion = @converter.convert end it "should have a start state" do @conversion.start_state.should_not be_nil end it "should have one transition on the start state" do @conversion.start_state.transitions.size.should == 1 end it "should transition back to itself" do @conversion.start_state.transitions.first.state.should equal(@conversion.start_state) end end describe "an nfa with start state leading to two different states on the same symbol" do before do @nfa.start_state.add_transition :symbol => :a @nfa.start_state.add_transition :symbol => :a @conversion = @converter.convert end it "should only have one transition out of the start state" do @conversion.start_state.transitions.size.should == 1 end end describe "an NFA with an epsilon transition (start -> a -> epsilon -> b)" do before do two = @nfa.start_state.add_transition :symbol => :a three = two.add_transition :symbol => Machine::EpsilonTransition four = three.add_transition :symbol => :b @conversion = @converter.convert end it "should have one transition coming from the start state" do @conversion.start_state.number_of_transitions.should == 1 end it "should have the first transition on an a" do @conversion.start_state.transitions.first.symbol.should equal(:a) end it "should have a second transition to a b" do second_state = @conversion.start_state.transitions.first.state second_state.transitions.size.should == 1 second_state.transitions.first.symbol.should equal(:b) end end describe "with an epsilon transition on the same symbol to two different final states" do before do two = @nfa.start_state.add_transition :symbol => :a three = @nfa.start_state.add_transition :symbol => :a @conversion = @converter.convert end it "should have only one transition out of the start state" do @conversion.start_state.transitions.size.should == 1 end it "should have the transition out of the start state on the symbol" do @conversion.start_state.transitions.first.symbol.should == :a end it "should transition to a new state with no transitions" do target_state = @conversion.start_state.transitions.first.state target_state.transitions.should == [] end end end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
86ba5a92075c80cb94b22774c13c23d6cdafbb8f
Exclude gems when rcov'ing
diff --git a/tasks/rspec.rake b/tasks/rspec.rake index 037b6e5..a7e743e 100644 --- a/tasks/rspec.rake +++ b/tasks/rspec.rake @@ -1,20 +1,20 @@ require 'spec/rake/spectask' require 'spec/rake/verify_rcov' desc 'Run the specs' Spec::Rake::SpecTask.new do |t| t.warning = false t.spec_opts = ["--color"] end desc "Create the html specdoc" Spec::Rake::SpecTask.new(:specdoc => :create_doc_directory) do |t| t.spec_opts = ["--format", "html:doc/specdoc.html"] end desc "Run all examples with RCov" Spec::Rake::SpecTask.new(:rcov) do |t| t.rcov = true - t.rcov_opts = ['--exclude', 'spec'] + t.rcov_opts = ['--exclude', 'spec', "--exclude", "gems"] t.rcov_dir = "doc/rcov" -end \ No newline at end of file +end
smtlaissezfaire/hopcroft
e9ff11c22be2b50a6e47b6673de71a4a25b0c97e
Add alias for now
diff --git a/lib/hopcroft/regex/base.rb b/lib/hopcroft/regex/base.rb index aa748de..100babc 100644 --- a/lib/hopcroft/regex/base.rb +++ b/lib/hopcroft/regex/base.rb @@ -1,50 +1,52 @@ module Hopcroft module Regex class Base def initialize(expr) @expression = expr end attr_reader :expression def ==(other) other.respond_to?(:to_regex_s) && to_regex_s == other.to_regex_s end def matches?(str) to_machine.matches? str end alias_method :matched_by?, :matches? def +(other) Concatenation.new(self, other) end def |(other) Alternation.new(self, other) end def to_regexp Regexp.new(to_regex_s) end alias_method :to_regex, :to_regexp - def to_machine + def to_nfa new_machine do |m, start_state| build_machine(start_state) end end + + alias_method :to_machine, :to_nfa private def new_machine returning Machine::StateMachine.new do |machine| yield machine, machine.start_state if block_given? end end end end end
smtlaissezfaire/hopcroft
e21ab63fc2146943e1053190dbfaaac5a01affd8
Add to README
diff --git a/README.rdoc b/README.rdoc index c366f92..7bdc75e 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,4 +1,35 @@ = Hopcroft A library for dealing with regular languages: Regexes and State Machines. +== Example + +If you can understand the following, welcome to the club! + + ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b") + => #<Hopcroft::Regex::Alternation:0x122698c @expressions=[#<Hopcroft::Regex::Char:0x12240ec @expression="a">, #<Hopcroft::Regex::Char:0x1224a4c @expression="b">]> + ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine + => #<Hopcroft::Machine::StateMachine:0x121f074 @start_state=State 1 {start: true, final: false, transitions: 2}> + ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine.to_dfa + => #<Hopcroft::Machine::StateMachine:0x120d630 @start_state=State 12 {start: true, final: false, transitions: 2}> + + ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine + => #<Hopcroft::Machine::StateMachine:0x5f1b1c @start_state=State 24 {start: true, final: false, transitions: 2}> + ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine.state_table + => + +-------------+------------+------------+--------------------------------------+ + | | b | a | Hopcroft::Machine::EpsilonTransition | + +-------------+------------+------------+--------------------------------------+ + | State 32 | * State 33 | | | + | State 30 | | * State 31 | | + | -> State 29 | | | State 30, State 32 | + +-------------+------------+------------+--------------------------------------+ + + ruby-1.8.6-p383 > Hopcroft::Regex.parse("a|b").to_machine.to_dfa.state_table + => + +-------------+----------+----------+ + | | a | b | + +-------------+----------+----------+ + | -> State 21 | State 22 | State 23 | + +-------------+----------+----------+ +
smtlaissezfaire/hopcroft
e6314e12a7ec0c0e9729b8c99b35f6d0e38dc818
Rename Regex.compile to Regex.parse
diff --git a/lib/hopcroft/regex.rb b/lib/hopcroft/regex.rb index 308919c..725a7e1 100644 --- a/lib/hopcroft/regex.rb +++ b/lib/hopcroft/regex.rb @@ -1,34 +1,34 @@ require "treetop" module Hopcroft module Regex SPECIAL_CHARS = [ DOT = ".", PLUS = "+", QUESTION = "?", STAR = "*", OPEN_BRACKET = "[", CLOSE_BRACKET = "]", ESCAPE_CHAR = "\\", ALTERNATION = "|" ] extend Using using :Base using :Char using :KleenStar using :Plus using :Dot using :CharacterClass using :OptionalSymbol using :Concatenation using :Alternation using :SyntaxNodes using :Parser - def self.compile(from_string) + def self.parse(from_string) Parser.parse(from_string) end end end diff --git a/spec/hopcoft/integration_spec.rb b/spec/hopcoft/integration_spec.rb index b2d1b60..5f46fc2 100644 --- a/spec/hopcoft/integration_spec.rb +++ b/spec/hopcoft/integration_spec.rb @@ -1,173 +1,173 @@ require File.expand_path(File.dirname(__FILE__) + "/../spec_helper") module Hopcroft describe "Integration tests" do describe "the regex /a/" do before do - @regex = Regex.compile("a") + @regex = Regex.parse("a") end it "should match 'a'" do @regex.should be_matched_by("a") end it "should not match 'b'" do @regex.should_not be_matched_by("b") end it "should not match 'abasdfasdf'" do @regex.should_not be_matched_by('abasdfasdf') end end describe "the regex /ab/" do before do - @regex = Regex.compile("ab") + @regex = Regex.parse("ab") end it "should match 'ab'" do @regex.should be_matched_by("ab") end it "should not match 'x'" do @regex.should_not be_matched_by("x") end it "should not match 'ba'" do @regex.should_not be_matched_by("ba") end end describe "the regex /a*/" do before do - @regex = Regex.compile("a*") + @regex = Regex.parse("a*") end it "should be matched by 'a'" do @regex.should be_matched_by("a") end it "should be matched by the empty string" do @regex.should be_matched_by("") end it "should be matched by 'aa'" do @regex.should be_matched_by("aa") end it "should be matched by 'aaa'" do @regex.should be_matched_by("aaa") end it "should not be matched by 'aab'" do @regex.should_not be_matched_by("aab") end end describe "the regex /a+/" do before do - @regex = Regex.compile("a+") + @regex = Regex.parse("a+") end it "should be matched by 'a'" do @regex.should be_matched_by("a") end it "should NOT be matched by the empty string" do @regex.should_not be_matched_by("") end it "should be matched by 'aa'" do @regex.should be_matched_by("aa") end it "should not be matched by 'aab'" do @regex.should_not be_matched_by("aab") end it "should be matched by 'aaa'" do @regex.matches?("aaa") @regex.should be_matched_by("aaa") end end describe "the regex /a|b/" do before do - @regex = Regex.compile("a|b") + @regex = Regex.parse("a|b") end it "should be matched by an 'a'" do @regex.should be_matched_by("a") end it "should be matched by a 'b'" do @regex.should be_matched_by("b") end it "should not be matched by a 'c'" do @regex.should_not be_matched_by("c") end it "should not be matched with the string 'ab'" do @regex.matched_by?("ab") @regex.should_not be_matched_by("ab") end end describe "the regex /(a|b)+/" do before do - @regex = Regex.compile("(a|b)+") + @regex = Regex.parse("(a|b)+") end it "should not match the empty string" do @regex.should_not be_matched_by("") end it "should match an a" do @regex.should be_matched_by("a") end it "should match 'b'" do @regex.should be_matched_by("b") end it "should match 'aaa'" do @regex.should be_matched_by("aaa") end it "should match 'bbb'" do @regex.should be_matched_by("bbb") end it "should match 'ababababbbaaa'" do @regex.should be_matched_by('ababababbbaaa') end it "should not be matched if it contains a different char" do @regex.should_not be_matched_by("ababbbbaacaab") end end describe "the regex (a|b)+x" do before do - @regex = Regex.compile("(a|b)+x") + @regex = Regex.parse("(a|b)+x") end it "should match 'ax'" do @regex.should be_matched_by("ax") end it "should match 'bx'" do @regex.should be_matched_by("bx") end it "should match 'ababx'" do @regex.should be_matched_by("ababx") end it "should not match 'x'" do @regex.should_not be_matched_by("x") end end end end
smtlaissezfaire/hopcroft
945c35a130262274e404ef6c22f64c72d0611c83
Display DFA's properly
diff --git a/lib/hopcroft/machine/table_displayer.rb b/lib/hopcroft/machine/table_displayer.rb index f52c205..0067843 100644 --- a/lib/hopcroft/machine/table_displayer.rb +++ b/lib/hopcroft/machine/table_displayer.rb @@ -1,67 +1,71 @@ require "terminal-table" require "facets/enumerable/map_with_index" module Hopcroft module Machine class TableDisplayer NEWLINE = "\n" EMPTY_TABLE_MESSAGE = "Empty table" def initialize(state_table_hash) @state_hash = state_table_hash end def to_a [header, body] end def header converted_table.header.map { |col| col.to_s } end def body converted_table.body.map do |row| row.map_with_index do |entry, index| if index == 0 text = decorate_start_state(entry) decorate_final_state(entry, text) else - entry.map { |state| decorate_final_state(state) }.join(", ") + if entry.respond_to?(:map) + entry.map { |state| decorate_final_state(state) }.join(", ") + else + decorate_final_state(entry) + end end end end end def to_s returning String.new do |s| s << NEWLINE s << table end end include Terminal::Table::TableHelper def table if @state_hash.empty? EMPTY_TABLE_MESSAGE else super(header, *body).to_s end end private def decorate_final_state(state, text = state.name) state.final? ? "* #{text}" : text end def decorate_start_state(state) state.start_state? ? "-> #{state.name}" : state.name end def converted_table @table ||= TableConverter.new(@state_hash) end end end end diff --git a/spec/hopcoft/machine/dfa_transition_table_spec.rb b/spec/hopcoft/machine/dfa_transition_table_spec.rb index 6063673..5f8c7b1 100644 --- a/spec/hopcoft/machine/dfa_transition_table_spec.rb +++ b/spec/hopcoft/machine/dfa_transition_table_spec.rb @@ -1,175 +1,185 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe DfaTransitionTable do before do @table = DfaTransitionTable.new @state = State.new end it "should have the start state as assignable" do @table.start_state = @state @table.start_state.should equal(@state) end describe "adding state changes" do before do @state_two = State.new end it "should be able to add a state change with a symbol" do @table.add_state_change(@state, @state_two, :symbol) @table.has_state_change?(@state, @state_two, :symbol).should be_true end it "should not have a state change if none are provided" do @table.has_state_change?(@state, @state_two, :symbol).should be_false end it "should not match the state change if with a different sym" do @table.add_state_change(@state, @state_two, :symbol) @table.has_state_change?(@state, @state_two, :bar).should be_false end it "should not match the state change with a different starting state" do @table.add_state_change(@state, @state_two, :symbol) @table.has_state_change?(mock('different state'), @state_two, :symbol).should be_false end it "should not match the state change with a different finishing state" do @table.add_state_change(@state, @state_two, :symbol) @table.has_state_change?(@state, mock('a different state'), :symbol).should be_false end it "should raise an error if a state change for the state & symbol has already been provided" do @table.add_state_change(@state, @state_two, :symbol) lambda { @table.add_state_change(@state, mock("another target"), :symbol) }.should raise_error(DfaTransitionTable::DuplicateStateError) end end describe "target_for" do before do @state_two = State.new end it "should be the to symbol of the state change" do @table.add_state_change(@state, @state_two, :symbol) @table.target_for(@state, :symbol).should == @state_two end it "should return nil if it cannot find the state" do @table.add_state_change(@state, @state_two, :symbol) @table.target_for(mock("a different state"), :symbol).should be_nil end it "should return nil if it cannot find the symbol" do @table.add_state_change(@state, @state_two, :symbol) @table.target_for(@state, :foo).should be_nil end end describe "to_hash" do it "should return a hash" do @table.to_hash.should be_a_kind_of(Hash) end it "should return a hash constructed from the table" do Hash.should_receive(:new).with(@table) @table.to_hash end end describe "initial_states" do it "should be the start state" do @table.start_state = @state @table.initial_state.should equal(@state) end end describe "next_transitions" do it "should be an alias for target_for" do @table.method(:next_transitions).should == @table.method(:target_for) end end describe "matches?" do it "should raise an error if there is no start state" do lambda { @table.matches?("foo") }.should raise_error(DfaTransitionTable::MissingStartState) end describe "with a start state which is a final state, with no transitions" do before do @state = State.new(:final => true) @table.start_state = @state end it "should match the start state with no input chars" do @table.should be_matched_by([]) end it "should not match when given an input symbol" do @table.should_not be_matched_by(["a"]) end end describe "with only a start state & no final states" do before do @state = State.new(:final => false) @table.start_state = @state end it "should not match with no input" do @table.should_not be_matched_by([]) end it "should not match when given an input symbol" do @table.should_not be_matched_by(["a"]) end end describe "with a start state which leads to a final state" do before do @state = State.new @final_state = State.new(:final => true) @table.start_state = @state @table.add_state_change @state, @final_state, "a" end it "should not match when given no input" do @table.should_not be_matched_by([]) end it "should match when given the one char" do @table.should be_matched_by(["a"]) end it "should not match when given a different char" do @table.should_not be_matched_by(["b"]) end it "should not match when given the input symbol repeatedly" do @table.should_not be_matched_by(["a", "a"]) end it "should return false if it does not match" do @table.matched_by?(["a", "a"]).should be_false end end end describe "inspect" do it "should call TableDisplayer" do TableDisplayer.should_receive(:new) @table.inspect end + + it "should output a display with rows + columns (it should not raise an error)" do + state1, state2 = State.new, State.new + + @table.add_state_change(state1, state2, :a_sym) + + lambda { + @table.inspect + }.should_not raise_error + end end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
1e2165fd61dc4bb400fb973f03354f74b7da06c5
Add StateMachine#to_dfa
diff --git a/lib/hopcroft/machine/state_machine.rb b/lib/hopcroft/machine/state_machine.rb index fa15b83..ebb9701 100644 --- a/lib/hopcroft/machine/state_machine.rb +++ b/lib/hopcroft/machine/state_machine.rb @@ -1,48 +1,52 @@ module Hopcroft module Machine class StateMachine def initialize(start_state = State.new) @start_state = start_state end attr_accessor :start_state def states [start_state, start_state.substates].flatten end def final_states states.select { |s| s.final? } end def matches_string?(str) matches_array? str.split("") end alias_method :matches?, :matches_string? def matches_array?(array) state_table.matches?(array) end def nfa_state_table returning NfaTransitionTable.new do |table| table.start_state = start_state start_state.add_transitions_to_table(table) end end alias_method :state_table, :nfa_state_table def deep_clone returning clone do |c| c.start_state = c.start_state.deep_clone end end def symbols state_table.symbols end + + def to_dfa + Converters::NfaToDfaConverter.new(self).convert + end end end end diff --git a/spec/hopcoft/machine/state_machine_spec.rb b/spec/hopcoft/machine/state_machine_spec.rb index 709ebcf..d3d8ff3 100644 --- a/spec/hopcoft/machine/state_machine_spec.rb +++ b/spec/hopcoft/machine/state_machine_spec.rb @@ -1,96 +1,123 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe StateMachine do before do @machine = StateMachine.new end it "should have a start state when beginning" do @machine.start_state.should be_a_kind_of(State) end it "should be able to add a start state" do state = State.new @machine.start_state = state @machine.start_state.should equal(state) end it "should accept a start state in the constructor" do state = State.new machine = StateMachine.new(state) machine.start_state.should equal(state) end it "should be able to traverse a list of states" do state = State.new second_state = State.new state.add_transition(:symbol => :foo, :state => second_state) @machine.start_state = state @machine.states.should == [state, second_state] end describe "building the transition table" do before do @machine = StateMachine.new end it "should match a transition of the start state to another state" do start_state = @machine.start_state second_state = start_state.add_transition :symbol => :foo @machine.state_table.targets_for(start_state, :foo).should == [second_state] end it "should match multiple transitions on the same key (a NFA)" do start_state = @machine.start_state state_one = start_state.add_transition :symbol => :foo state_two = start_state.add_transition :symbol => :foo @machine.state_table.targets_for(start_state, :foo).should == [state_one, state_two] end it "should be able to have a state with a transition to itself" do start_state = @machine.start_state start_state.add_transition :symbol => :foo, :state => start_state @machine.state_table.targets_for(start_state, :foo).should == [start_state] end it "should add a start state with no transitions to the table" do start_state = @machine.start_state @machine.state_table.start_state.should == start_state end end describe "deep_copy" do before do @machine = StateMachine.new end it "should create a new instance" do @machine.deep_clone.should_not equal(@machine) end it "should have a cloned start state" do @machine.deep_clone.start_state.should_not equal(@machine.start_state) end it "should have the cloned start state as a final state if the original machine did" do @machine.start_state.final_state = true @machine.deep_clone.start_state.should be_a_final_state end it "should call deep_clone on the start state" do @machine.start_state.should_receive(:deep_clone) @machine.deep_clone end end + + describe "to_dfa" do + before do + @machine = StateMachine.new + end + + it "should call the NFA to Dfa converter" do + converter = mock 'converter', :convert => true + + Converters::NfaToDfaConverter.should_receive(:new).with(@machine).and_return converter + @machine.to_dfa + end + + it "should call convert" do + converter = mock 'converter', :convert => true + Converters::NfaToDfaConverter.stub!(:new).and_return(converter) + + converter.should_receive(:convert) + @machine.to_dfa + end + + it "should return a new state machine" do + dfa = @machine.to_dfa + dfa.should be_a_kind_of(StateMachine) + dfa.should_not equal(@machine) + end + end end end end
smtlaissezfaire/hopcroft
6f52bbdc0be0188e3daa4592ede7a02d8dbf1643
Alias state_table => nfa_state_table
diff --git a/lib/hopcroft/machine/state_machine.rb b/lib/hopcroft/machine/state_machine.rb index 115e3e2..fa15b83 100644 --- a/lib/hopcroft/machine/state_machine.rb +++ b/lib/hopcroft/machine/state_machine.rb @@ -1,46 +1,48 @@ module Hopcroft module Machine class StateMachine def initialize(start_state = State.new) @start_state = start_state end attr_accessor :start_state def states [start_state, start_state.substates].flatten end def final_states states.select { |s| s.final? } end def matches_string?(str) matches_array? str.split("") end alias_method :matches?, :matches_string? def matches_array?(array) state_table.matches?(array) end - def state_table + def nfa_state_table returning NfaTransitionTable.new do |table| table.start_state = start_state start_state.add_transitions_to_table(table) end end + alias_method :state_table, :nfa_state_table + def deep_clone returning clone do |c| c.start_state = c.start_state.deep_clone end end def symbols state_table.symbols end end end end
smtlaissezfaire/hopcroft
1f259b05b1ce2eb4f8f94866127b0cee50b3cc4d
Add more specs
diff --git a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb index 17a12f2..5244d3d 100644 --- a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb +++ b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb @@ -1,136 +1,159 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Converters describe NfaToDfaConverter do before do @nfa = Machine::StateMachine.new end it "should take an state machine" do NfaToDfaConverter.new(@nfa).nfa.should equal(@nfa) end describe "conversion" do before do @converter = NfaToDfaConverter.new(@nfa) end it "should build a new state machine" do @converter.convert.should be_a_kind_of(Machine::StateMachine) end it "should have a start state" do @converter.convert.start_state.should_not be_nil end it "should keep a machine with a start state + no other states" do @converter.convert.start_state.transitions.should == [] end describe "with a dfa: state1(start) -> state2" do it "should create a new machine a transition" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end it "should create the new machine with the symbol :foo" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:foo) end it "should use the correct symbol" do @nfa.start_state.add_transition :symbol => :bar conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:bar) end it "should not have an identical (object identical) start state" do conversion = @converter.convert @nfa.start_state.should_not equal(conversion.start_state) end end describe "a dfa with state1 -> state2 -> state3" do before do state2 = @nfa.start_state.add_transition :symbol => :foo state3 = state2.add_transition :symbol => :bar end it "should have a transition to state2" do conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end it "should have a transition to state3" do conversion = @converter.convert conversion.start_state.transitions.first.state.transitions.size.should == 1 end end describe "a dfa with a start state which loops back to itself (on a sym)" do before do start_state = @nfa.start_state start_state.add_transition :symbol => :f, :state => start_state @conversion = @converter.convert end it "should have a start state" do @conversion.start_state.should_not be_nil end it "should have one transition on the start state" do @conversion.start_state.transitions.size.should == 1 end it "should transition back to itself" do @conversion.start_state.transitions.first.state.should equal(@conversion.start_state) end end describe "an nfa with start state leading to two different states on the same symbol" do before do @nfa.start_state.add_transition :symbol => :a @nfa.start_state.add_transition :symbol => :a @conversion = @converter.convert end it "should only have one transition out of the start state" do @conversion.start_state.transitions.size.should == 1 end end describe "an NFA with an epsilon transition (start -> a -> epsilon -> b)" do before do two = @nfa.start_state.add_transition :symbol => :a three = two.add_transition :symbol => Machine::EpsilonTransition four = three.add_transition :symbol => :b @conversion = @converter.convert end it "should have one transition coming from the start state" do @conversion.start_state.number_of_transitions.should == 1 end it "should have the first transition on an a" do @conversion.start_state.transitions.first.symbol.should equal(:a) end it "should have a second transition to a b" do second_state = @conversion.start_state.transitions.first.state second_state.transitions.size.should == 1 second_state.transitions.first.symbol.should equal(:b) end end + + describe "with an epsilon transition on the same symbol to two different final states" do + before do + two = @nfa.start_state.add_transition :symbol => :a + three = @nfa.start_state.add_transition :symbol => :a + + @conversion = @converter.convert + end + + it "should have only one transition out of the start state" do + @conversion.start_state.transitions.size.should == 1 + end + + it "should have the transition out of the start state on the symbol" do + @conversion.start_state.transitions.first.symbol.should == :a + end + + it "should transition to a new state with no transitions" do + target_state = @conversion.start_state.transitions.first.state + + target_state.transitions.should == [] + end + end end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
c556e41cbbfd45644960681a1cae42d5644febf1
Add a hacky & incomplete DFA->NFA with epsilon closure.
diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb index 2c852f8..a33e935 100644 --- a/lib/hopcroft/converters/nfa_to_dfa_converter.rb +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -1,83 +1,95 @@ module Hopcroft module Converters class NfaToDfaConverter + include Machine::StateMachineHelpers + def initialize(nfa) @nfa = nfa @nfa_states = {} @nfa_to_dfa_states = {} end attr_reader :nfa def convert - start_state = @nfa.start_state + start_state = [@nfa.start_state] @nfa_states = { start_state => false } returning new_machine do |dfa| - dfa.start_state = find_or_create_state(nfa.start_state) + dfa.start_state = find_or_create_state(start_state) while nfa_state = unmarked_states.first mark_state(nfa_state) - + symbols.each do |sym| - if target_nfa_state = move(nfa_state, sym) - add_nfa_state(target_nfa_state) - find_or_create_state(nfa_state).add_transition :symbol => sym, :state => find_or_create_state(target_nfa_state) + target_nfa_states = move(epsilon_closure(nfa_state), sym) + + if target_nfa_states.any? + add_nfa_state(target_nfa_states) + find_or_create_state(nfa_state).add_transition :symbol => sym, :state => find_or_create_state(target_nfa_states) end end end end end private def unmarked_states returning [] do |array| @nfa_states.each do |nfa_state, marked| if !marked array << nfa_state end end end end def add_nfa_state(nfa_state) if !@nfa_states.has_key?(nfa_state) @nfa_states[nfa_state] = false end end def mark_state(nfa_state) @nfa_states[nfa_state] = true end def symbols @nfa.symbols end def move(nfa_states, symbol) - if transition = nfa_states.transitions.detect { |t| t.symbol == symbol } - transition.state - else - nil + target_transitions = [] + + nfa_states.each do |state| + additional_transitions = state.transitions.select { |t| t.symbol == symbol } + target_transitions.concat(additional_transitions) end + + target_transitions.map { |t| t.state } end def find_or_create_state(nfa_states) + nfa_states = ordered_nfa_states(nfa_states) find_dfa_corresponding_to_nfa_state(nfa_states) || new_dfa_state(nfa_states) end def find_dfa_corresponding_to_nfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] end def new_dfa_state(nfa_states) @nfa_to_dfa_states[nfa_states] = Machine::State.new end + + def ordered_nfa_states(nfa_states) + nfa_states.sort_by { |state| state.id } + end def new_machine Machine::StateMachine.new end end end end \ No newline at end of file diff --git a/lib/hopcroft/machine/state.rb b/lib/hopcroft/machine/state.rb index 16681a2..2f9220c 100644 --- a/lib/hopcroft/machine/state.rb +++ b/lib/hopcroft/machine/state.rb @@ -1,128 +1,132 @@ module Hopcroft module Machine class State include Identifiable def initialize(options={}) track_id @start_state = options[:start_state] if options.has_key?(:start_state) @final_state = options[:final] if options.has_key?(:final) assign_name(options) end attr_reader :name alias_method :to_s, :name def inspect "#{name} {start: #{start_state?}, final: #{final_state?}, transitions: #{transitions.size}}" end def transitions @transitions ||= [] end attr_writer :transitions def epsilon_transitions transitions.select { |t| t.epsilon_transition? } end + + def number_of_transitions + transitions.size + end # Accepts the following hash arguments: # # :machine => m (optional). Links current state to start state of machine # given with an epsilon transition. # :start_state => true | false. Make the state a start state. Defaults to false # :final => true | false. Make the state a final state. Defaults to false # :state => a_state (if none passed, a new one is constructed) # :symbol => Symbol to transition to. # :epsilon => An Epsilon Transition instead of a regular symbol transition # :any => An any symbol transition. Equivalent to a regex '.' # def add_transition(args={}) args[:start_state] = false unless args.has_key?(:start_state) if args[:machine] machine = args[:machine] args[:state] = machine.start_state args[:state].start_state = false args[:epsilon] = true else args[:state] ||= State.new(args) end returning args[:state] do |state| transitions << transition_for(args, state) yield(state) if block_given? state end end def transition_for(args, state) if args[:epsilon] EpsilonTransition.new(state) elsif args[:any] AnyCharTransition.new(state) else Transition.new(args[:symbol], state) end end def start_state? @start_state.equal?(false) ? false : true end attr_writer :start_state def final_state? @final_state ? true : false end alias_method :final?, :final_state? attr_writer :final_state def substates(excluded_states = []) returning [] do |list| follow_states.each do |state| unless excluded_states.include?(state) excluded_states << state list.push state list.push *state.substates(excluded_states) end end end end def follow_states(excluded_states = []) transitions.map { |t| t.state }.reject { |s| excluded_states.include?(s) } end def add_transitions_to_table(table) transitions.each do |transition| to = transition.to unless table.has_state_change?(self, to, transition.symbol) table.add_state_change(self, to, transition.symbol) transition.to.add_transitions_to_table(table) end end end def deep_clone returning clone do |c| c.transitions = transitions.map { |t| t.deep_clone } end end private def assign_name(options) @name = options[:name] ? options[:name] : "State #{@id}" end end end end diff --git a/lib/hopcroft/machine/state_machine_helpers.rb b/lib/hopcroft/machine/state_machine_helpers.rb index bc35ce9..26adbc3 100644 --- a/lib/hopcroft/machine/state_machine_helpers.rb +++ b/lib/hopcroft/machine/state_machine_helpers.rb @@ -1,26 +1,34 @@ module Hopcroft module Machine module StateMachineHelpers - def epsilon_closure(state_list) + def epsilon_closure(state_or_state_list) + if state_or_state_list.is_a?(Machine::State) + epsilon_closure_for_state(state_or_state_list) + else + epsilon_closure_for_state_list(state_or_state_list) + end + end + + private + + def epsilon_closure_for_state_list(state_list) returning [] do |return_list| state_list.each do |state| return_list.concat(epsilon_closure_for_state(state)) end end end - private - def epsilon_closure_for_state(state, seen_states = []) returning [] do |set| if !seen_states.include?(state) set << state state.epsilon_transitions.each do |transition| set.concat(epsilon_closure_for_state(transition.state, seen_states << state)) end end end end end end end diff --git a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb index 787247a..17a12f2 100644 --- a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb +++ b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb @@ -1,112 +1,136 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Converters describe NfaToDfaConverter do before do @nfa = Machine::StateMachine.new end it "should take an state machine" do NfaToDfaConverter.new(@nfa).nfa.should equal(@nfa) end describe "conversion" do before do @converter = NfaToDfaConverter.new(@nfa) end it "should build a new state machine" do @converter.convert.should be_a_kind_of(Machine::StateMachine) end it "should have a start state" do @converter.convert.start_state.should_not be_nil end it "should keep a machine with a start state + no other states" do @converter.convert.start_state.transitions.should == [] end describe "with a dfa: state1(start) -> state2" do it "should create a new machine a transition" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end it "should create the new machine with the symbol :foo" do @nfa.start_state.add_transition :symbol => :foo conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:foo) end it "should use the correct symbol" do @nfa.start_state.add_transition :symbol => :bar conversion = @converter.convert conversion.start_state.transitions.first.symbol.should equal(:bar) end it "should not have an identical (object identical) start state" do conversion = @converter.convert @nfa.start_state.should_not equal(conversion.start_state) end end describe "a dfa with state1 -> state2 -> state3" do before do state2 = @nfa.start_state.add_transition :symbol => :foo state3 = state2.add_transition :symbol => :bar end it "should have a transition to state2" do conversion = @converter.convert conversion.start_state.transitions.size.should == 1 end it "should have a transition to state3" do conversion = @converter.convert conversion.start_state.transitions.first.state.transitions.size.should == 1 end end describe "a dfa with a start state which loops back to itself (on a sym)" do before do start_state = @nfa.start_state start_state.add_transition :symbol => :f, :state => start_state @conversion = @converter.convert end it "should have a start state" do @conversion.start_state.should_not be_nil end it "should have one transition on the start state" do @conversion.start_state.transitions.size.should == 1 end it "should transition back to itself" do @conversion.start_state.transitions.first.state.should equal(@conversion.start_state) end end describe "an nfa with start state leading to two different states on the same symbol" do before do @nfa.start_state.add_transition :symbol => :a @nfa.start_state.add_transition :symbol => :a @conversion = @converter.convert end it "should only have one transition out of the start state" do @conversion.start_state.transitions.size.should == 1 end end + + describe "an NFA with an epsilon transition (start -> a -> epsilon -> b)" do + before do + two = @nfa.start_state.add_transition :symbol => :a + three = two.add_transition :symbol => Machine::EpsilonTransition + four = three.add_transition :symbol => :b + + @conversion = @converter.convert + end + + it "should have one transition coming from the start state" do + @conversion.start_state.number_of_transitions.should == 1 + end + + it "should have the first transition on an a" do + @conversion.start_state.transitions.first.symbol.should equal(:a) + end + + it "should have a second transition to a b" do + second_state = @conversion.start_state.transitions.first.state + second_state.transitions.size.should == 1 + second_state.transitions.first.symbol.should equal(:b) + end + end end end end end \ No newline at end of file
smtlaissezfaire/hopcroft
40dc378a38c08e097c7109fcb3e2282d2e3a4d90
Add NFA->DFA conversion for non-epsilon transitioning NFA state machines
diff --git a/lib/hopcroft.rb b/lib/hopcroft.rb index 926c2cb..17153c2 100644 --- a/lib/hopcroft.rb +++ b/lib/hopcroft.rb @@ -1,11 +1,12 @@ require "using" require "facets/kernel/returning" module Hopcroft extend Using Using.default_load_scheme = :autoload using :Regex using :Machine + using :Converters end diff --git a/lib/hopcroft/converters.rb b/lib/hopcroft/converters.rb new file mode 100644 index 0000000..3a9a05d --- /dev/null +++ b/lib/hopcroft/converters.rb @@ -0,0 +1,7 @@ +module Hopcroft + module Converters + extend Using + + using :NfaToDfaConverter + end +end \ No newline at end of file diff --git a/lib/hopcroft/converters/nfa_to_dfa_converter.rb b/lib/hopcroft/converters/nfa_to_dfa_converter.rb new file mode 100644 index 0000000..2c852f8 --- /dev/null +++ b/lib/hopcroft/converters/nfa_to_dfa_converter.rb @@ -0,0 +1,83 @@ +module Hopcroft + module Converters + class NfaToDfaConverter + def initialize(nfa) + @nfa = nfa + @nfa_states = {} + @nfa_to_dfa_states = {} + end + + attr_reader :nfa + + def convert + start_state = @nfa.start_state + @nfa_states = { start_state => false } + + returning new_machine do |dfa| + dfa.start_state = find_or_create_state(nfa.start_state) + + while nfa_state = unmarked_states.first + mark_state(nfa_state) + + symbols.each do |sym| + if target_nfa_state = move(nfa_state, sym) + add_nfa_state(target_nfa_state) + find_or_create_state(nfa_state).add_transition :symbol => sym, :state => find_or_create_state(target_nfa_state) + end + end + end + end + end + + private + + def unmarked_states + returning [] do |array| + @nfa_states.each do |nfa_state, marked| + if !marked + array << nfa_state + end + end + end + end + + def add_nfa_state(nfa_state) + if !@nfa_states.has_key?(nfa_state) + @nfa_states[nfa_state] = false + end + end + + def mark_state(nfa_state) + @nfa_states[nfa_state] = true + end + + def symbols + @nfa.symbols + end + + def move(nfa_states, symbol) + if transition = nfa_states.transitions.detect { |t| t.symbol == symbol } + transition.state + else + nil + end + end + + def find_or_create_state(nfa_states) + find_dfa_corresponding_to_nfa_state(nfa_states) || new_dfa_state(nfa_states) + end + + def find_dfa_corresponding_to_nfa_state(nfa_states) + @nfa_to_dfa_states[nfa_states] + end + + def new_dfa_state(nfa_states) + @nfa_to_dfa_states[nfa_states] = Machine::State.new + end + + def new_machine + Machine::StateMachine.new + end + end + end +end \ No newline at end of file diff --git a/lib/hopcroft/machine/nfa_transition_table.rb b/lib/hopcroft/machine/nfa_transition_table.rb index c731d35..d883544 100644 --- a/lib/hopcroft/machine/nfa_transition_table.rb +++ b/lib/hopcroft/machine/nfa_transition_table.rb @@ -1,84 +1,88 @@ module Hopcroft module Machine class NfaTransitionTable < TransitionTable def start_state=(start_state) self[start_state] ||= {} super end # Create a transition without marking appropriate start states def add_state_change(from_state, to_state, transition_symbol) sym = transition_symbol self[from_state] ||= {} self[from_state][sym] ||= [] self[from_state][sym] << to_state end def has_state_change?(from_state, to_state, transition_symbol) super && self[from_state][transition_symbol].include?(to_state) end def targets_for(state, transition_sym) find_targets_matching(state, transition_sym) do |target| epsilon_states_following(target) end end def initial_states [start_state] + epsilon_states_following(start_state) end def next_transitions(states, sym) states.map { |s| targets_for(s, sym) }.compact.flatten end def matches?(input_array, current_states = initial_states) raise_if_no_start_state input_array.each do |sym| current_states = next_transitions(current_states, sym.to_sym) end current_states.any? { |state| state.final? } end + def symbols + values.map { |v| v.keys }.flatten.uniq.reject { |sym| sym == EpsilonTransition } + end + private def epsilon_states_following(state) find_targets_matching(state, EpsilonTransition) do |target| epsilon_states_following(target) end end def find_targets_matching(state, transition_sym, &recursion_block) returning Array.new do |a| direct_targets = find_targets_for(state, transition_sym) append a, direct_targets direct_targets.each do |target| append a, recursion_block.call(target) end end end def find_targets_for(state, transition_sym) returning Array.new do |a| if state = self[state] if state[transition_sym] append a, state[transition_sym] end if state[AnyCharTransition] && transition_sym != EpsilonTransition append a, state[AnyCharTransition] end end end end def append(array1, array2) array1.push *array2 end end end end diff --git a/lib/hopcroft/machine/state_machine.rb b/lib/hopcroft/machine/state_machine.rb index a762a3c..115e3e2 100644 --- a/lib/hopcroft/machine/state_machine.rb +++ b/lib/hopcroft/machine/state_machine.rb @@ -1,42 +1,46 @@ module Hopcroft module Machine class StateMachine def initialize(start_state = State.new) @start_state = start_state end attr_accessor :start_state def states [start_state, start_state.substates].flatten end def final_states states.select { |s| s.final? } end def matches_string?(str) matches_array? str.split("") end alias_method :matches?, :matches_string? def matches_array?(array) state_table.matches?(array) end def state_table returning NfaTransitionTable.new do |table| table.start_state = start_state start_state.add_transitions_to_table(table) end end def deep_clone returning clone do |c| c.start_state = c.start_state.deep_clone end end + + def symbols + state_table.symbols + end end end end diff --git a/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb new file mode 100644 index 0000000..787247a --- /dev/null +++ b/spec/hopcoft/converters/nfa_to_dfa_converter_spec.rb @@ -0,0 +1,112 @@ +require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") + +module Hopcroft + module Converters + describe NfaToDfaConverter do + before do + @nfa = Machine::StateMachine.new + end + + it "should take an state machine" do + NfaToDfaConverter.new(@nfa).nfa.should equal(@nfa) + end + + describe "conversion" do + before do + @converter = NfaToDfaConverter.new(@nfa) + end + + it "should build a new state machine" do + @converter.convert.should be_a_kind_of(Machine::StateMachine) + end + + it "should have a start state" do + @converter.convert.start_state.should_not be_nil + end + + it "should keep a machine with a start state + no other states" do + @converter.convert.start_state.transitions.should == [] + end + + describe "with a dfa: state1(start) -> state2" do + it "should create a new machine a transition" do + @nfa.start_state.add_transition :symbol => :foo + + conversion = @converter.convert + conversion.start_state.transitions.size.should == 1 + end + + it "should create the new machine with the symbol :foo" do + @nfa.start_state.add_transition :symbol => :foo + + conversion = @converter.convert + conversion.start_state.transitions.first.symbol.should equal(:foo) + end + + it "should use the correct symbol" do + @nfa.start_state.add_transition :symbol => :bar + + conversion = @converter.convert + conversion.start_state.transitions.first.symbol.should equal(:bar) + end + + it "should not have an identical (object identical) start state" do + conversion = @converter.convert + @nfa.start_state.should_not equal(conversion.start_state) + end + end + + describe "a dfa with state1 -> state2 -> state3" do + before do + state2 = @nfa.start_state.add_transition :symbol => :foo + state3 = state2.add_transition :symbol => :bar + end + + it "should have a transition to state2" do + conversion = @converter.convert + conversion.start_state.transitions.size.should == 1 + end + + it "should have a transition to state3" do + conversion = @converter.convert + conversion.start_state.transitions.first.state.transitions.size.should == 1 + end + end + + describe "a dfa with a start state which loops back to itself (on a sym)" do + before do + start_state = @nfa.start_state + start_state.add_transition :symbol => :f, :state => start_state + + @conversion = @converter.convert + end + + it "should have a start state" do + @conversion.start_state.should_not be_nil + end + + it "should have one transition on the start state" do + @conversion.start_state.transitions.size.should == 1 + end + + it "should transition back to itself" do + @conversion.start_state.transitions.first.state.should equal(@conversion.start_state) + end + end + + describe "an nfa with start state leading to two different states on the same symbol" do + before do + @nfa.start_state.add_transition :symbol => :a + @nfa.start_state.add_transition :symbol => :a + + @conversion = @converter.convert + end + + it "should only have one transition out of the start state" do + @conversion.start_state.transitions.size.should == 1 + end + end + end + end + end +end \ No newline at end of file diff --git a/spec/hopcoft/machine/nfa_transition_table_spec.rb b/spec/hopcoft/machine/nfa_transition_table_spec.rb index 3e73c2a..b4045ee 100644 --- a/spec/hopcoft/machine/nfa_transition_table_spec.rb +++ b/spec/hopcoft/machine/nfa_transition_table_spec.rb @@ -1,249 +1,299 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") module Hopcroft module Machine describe NfaTransitionTable do describe "adding a state change" do before do @table = NfaTransitionTable.new end it "should create a two dimensional entry, with [from_state][transition] = [to_state]" do from = mock(State, :start_state? => false) to = mock(State, :start_state? => false) @table.add_state_change(from, to, :a) @table.targets_for(from, :a).should == [to] end it "should be able to use strings when finding a start state" do from = mock State, :start_state? => true, :final? => false to = mock State, :start_state? => false, :final? => true @table.add_state_change(from, to, :a) @table.start_state = from @table.matches?("a").should be_true end it "should be able to use multiple transitions from the same state" do from = mock(State, :start_state? => false) first_result = mock(State, :start_state? => false) second_result = mock(State, :start_state? => false) @table.start_state = from @table.add_state_change(from, first_result, :a) @table.add_state_change(from, second_result, :b) @table.targets_for(from, :a).should == [first_result] @table.targets_for(from, :b).should == [second_result] end it "should be able to use the same transition symbol to different states (for an NFA)" do from = mock(State, :start_state? => false) first_result = mock(State, :start_state? => false) second_result = mock(State, :start_state? => false) @table.add_state_change(from, first_result, :a) @table.add_state_change(from, second_result, :a) @table.targets_for(from, :a).should == [first_result, second_result] end it "should have a transition for an 'any' transition" do from = State.new :start_state => true to = from.add_transition :any => true transition = from.transitions.first.symbol @table.add_state_change from, to, transition @table.targets_for(from, :a).should == [to] end end describe "targets_for" do before do @table = NfaTransitionTable.new @state = mock(State, :start_state? => false, :final? => false) @transition = :foo end it "should reutrn an empty array if it indexes the state, but no transitions for that state" do @table.add_state_change(@state, @state, :foo) @table.targets_for(@state, :bar).should == [] end it "should return an empty array if it does not index the state" do @table.targets_for(@state, :foo).should == [] end end describe "matching a symbol" do before do @table = NfaTransitionTable.new end it "should match if one symbol in the table, and the symbol is given" do start_state = mock(State, :final? => false, :start_state? => true) final_state = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change(start_state, final_state, :foo) @table.matches?([:foo]).should be_true end it "should not match when it cannot index the transition" do start_state = mock(State, :final? => false, :start_state? => true) final_state = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change(start_state, final_state, :foo) @table.matches?([:bar]).should be_false end it "should not match if the last state in the input is not a final state" do start_state = mock(State, :final? => false, :start_state? => true) final_state = mock(State, :final? => false, :start_state? => false) @table.start_state = start_state @table.add_state_change(start_state, final_state, :foo) @table.matches?([:foo]).should be_false end it "should raise an error if there is no start state" do lambda { @table.matches?([:foo]) }.should raise_error(NfaTransitionTable::MissingStartState) end it "should match when following two symbols" do start_state = mock(State, :final? => false, :start_state? => true) state_one = mock(State, :final? => false, :start_state? => false) state_two = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_one, :one @table.add_state_change state_one, state_two, :two @table.matches?([:one, :two]).should be_true end it "should not match when following two symbols, and the last is not a final state" do start_state = mock(State, :final? => false, :start_state? => true) state_one = mock(State, :final? => false, :start_state? => false) state_two = mock(State, :final? => false, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_one, :one @table.add_state_change state_one, state_two, :two @table.matches?([:one, :two]).should be_false end it "should match a NFA, where a start state leads to one of two possible final states" do start_state = mock(State, :final? => false, :start_state? => true) state_one = mock(State, :final? => false, :start_state? => false) state_two = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_one, :one @table.add_state_change start_state, state_two, :one @table.matches?([:one]).should be_true end it "should not match when the one state does not transition to the other" do start_state = mock(State, :final? => false, :start_state? => true) state_one = mock(State, :final? => false, :start_state? => false) state_two = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_one, :one @table.add_state_change start_state, state_two, :two @table.matches?([:one, :two]).should be_false end it "should not consume any chars under an epsilon transition" do start_state = mock(State, :final? => false, :start_state? => true) state_two = mock(State, :final? => true, :start_state? => false) @table.start_state = start_state @table.add_state_change start_state, state_two, EpsilonTransition @table.matches?([]).should be_true end end describe "inspect" do before do @table = NfaTransitionTable.new @displayer = mock TableDisplayer end it "should output a state table" do TableDisplayer.should_receive(:new).with(@table).and_return @displayer @displayer.should_receive(:to_s) @table.inspect end it "should display 'Empty table' when empty" do @table.inspect.should == "\nEmpty table" end it "should be able to display a start state with no transitions" do start_state = State.new(:start_state => true, :name => "Foo") @table.start_state = start_state @table.inspect.should include("Foo") end end describe "to_hash" do it "should return a hash" do NfaTransitionTable.new.to_hash.class.should == Hash end end describe "initial states" do describe "for a start_state to an epsilon transition" do # +--------------+--------------------------------------+-------------+ # | | Hopcroft::Machine::EpsilonTransition | a | # +--------------+--------------------------------------+-------------+ # | -> State 207 | State 208 | | # | State 208 | | * State 209 | # +--------------+--------------------------------------+-------------+ before do @state1 = State.new :start_state => true, :name => "State 1" @state2 = State.new :start_state => false, :name => "State 2" @state3 = State.new :start_state => false, :name => "State 3", :final_state => true @table = NfaTransitionTable.new @table.add_state_change @state1, @state2, EpsilonTransition @table.add_state_change @state2, @state3, :a @table.start_state = @state1 end it "should have state 1 as an initial state (it is a start state)" do @table.initial_states.should include(@state1) end it "should have state 2 as an initial state (it has an epsilon transition from the start state)" do @table.initial_states.should include(@state2) end it "should not have state 3 as an initial state" do @table.initial_states.should_not include(@state3) end end end + + describe "symbols" do + before do + @table = NfaTransitionTable.new + + @state1 = State.new :start_state => true, :name => "State 1" + @state2 = State.new :start_state => false, :name => "State 2" + @state3 = State.new :start_state => false, :name => "State 3", :final_state => true + end + + it "should have no symbols with no transitions" do + @table.symbols.should == [] + end + + it "should have no symbols with a start state, but no transitions" do + @table.start_state = @state1 + @table.symbols.should == [] + end + + it "should report a regular symbol" do + @table.start_state = @state1 + @table.add_state_change @state1, @state2, :foo + + @table.symbols.should == [:foo] + end + + it "should report several regular symbols" do + @table.start_state = @state1 + @table.add_state_change @state1, @state2, :foo + @table.add_state_change @state2, @state3, :bar + + @table.symbols.should include(:foo) + @table.symbols.should include(:bar) + end + + it "should report a symbol only once" do + @table.start_state = @state1 + @table.add_state_change @state1, @state2, :foo + @table.add_state_change @state2, @state3, :foo + + @table.symbols.should == [:foo] + end + + it "should not report epsilon symbols" do + @table.start_state = @state1 + @table.add_state_change @state1, @state2, EpsilonTransition + + @table.symbols.should == [] + end + end end end end