Skip to content

Commit deaea17

Browse files
feat: select code to search
fix #225
1 parent 494a7db commit deaea17

File tree

4 files changed

+36
-0
lines changed

4 files changed

+36
-0
lines changed

package.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@
8080
"light": "media/expand-light.svg",
8181
"dark": "media/expand-dark.svg"
8282
}
83+
},
84+
{
85+
"command": "ast-grep.searchByCode",
86+
"title": "ast-grep: Search by Code"
8387
}
8488
],
8589
"menus": {
@@ -90,6 +94,14 @@
9094
"when": "explorerResourceIsFolder"
9195
}
9296
],
97+
98+
"editor/context": [
99+
{
100+
"command": "ast-grep.searchByCode",
101+
"when": "editorHasSelection",
102+
"group": "navigation"
103+
}
104+
],
93105
"view/title": [
94106
{
95107
"command": "ast-grep.collapseAll",

src/extension/search.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { SgSearch, DisplayResult, SearchQuery } from '../types'
1111
export function activateSearch(context: ExtensionContext) {
1212
context.subscriptions.push(
1313
commands.registerCommand('ast-grep.searchInFolder', findInFolder),
14+
commands.registerCommand('ast-grep.searchByCode', searchByCode),
1415
)
1516
}
1617

@@ -176,3 +177,14 @@ parentPort.onMessage('search', async payload => {
176177
})
177178
parentPort.postMessage('searchEnd', payload)
178179
})
180+
181+
function searchByCode() {
182+
const editor = window.activeTextEditor
183+
if (!editor) {
184+
return
185+
}
186+
const selection = editor.selection
187+
const text = editor.document.getText(selection)
188+
commands.executeCommand('ast-grep.search.input.focus')
189+
parentPort.postMessage('searchByCode', { text })
190+
}

src/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ export interface ParentToChild {
6969
refreshAllSearch: unknown
7070
clearSearchResults: unknown
7171
toggleAllSearch: unknown
72+
searchByCode: { text: string }
7273
}
7374

7475
export interface Diff {

src/webview/hooks/useQuery.tsx

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ export function useSearchField(key: keyof typeof LS_KEYS) {
4141
useEffect(() => {
4242
searchQuery[key] = field
4343
}, [field, key])
44+
// this is really BAD code :(
45+
useEffect(() => {
46+
if (key !== 'pattern') {
47+
return
48+
}
49+
childPort.onMessage('searchByCode', ({ text }) => {
50+
searchQuery[key] = field
51+
setField(text)
52+
refreshResult()
53+
})
54+
}, [key])
4455
useDebounce(refreshResult, 150, [field])
4556
return [field, setField] as const
4657
}

0 commit comments

Comments
 (0)