summaryrefslogtreecommitdiff
path: root/gwic.go
blob: 5cbbd937d81d6b626bd91b86e29b7f1de9ed3f82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strings"
	"text/tabwriter"
)

type queue []string

func (q *queue) insert(s string) {
}

func printWithContext(all []string, ind, ctxlen int) {
	var slice []string
	slice = append(slice, "\""+all[ind]+"\"")

	if len(all[:ind]) < ctxlen {
		slice = append(all[:ind], slice...)
	} else {
		slice = append(all[ind-ctxlen:ind], slice...)
	}

	if len(all[ind:]) < ctxlen {
		slice = append(slice, all[ind+1:]...)
	} else {
		slice = append(slice, all[ind+1:ind+ctxlen]...)
	}

	fstr := strings.Join(slice, "\t")
	fmt.Fprintf(tw, "%s\n", fstr)
}

var tw *tabwriter.Writer

func main() {
	flag.Parse()
	kw := flag.Arg(0)
	if len(kw) == 0 {
		fmt.Printf("Need string to search for. Exiting...\n")
		os.Exit(1)
	}
	tw = tabwriter.NewWriter(os.Stdout, 1, 2, 1, ' ', 0)

	reader := bufio.NewReader(os.Stdin)
	all, err := ioutil.ReadAll(reader)
	if err != nil {
		fmt.Printf("Could not read everything because there was an error: %q. Exiting\n", err)
		os.Exit(1)
	}

	splitreg := regexp.MustCompile("[ \t\n]")
	splline := splitreg.Split(string(all), -1)
	for i, w := range splline {
		index := strings.Index(w, kw)
		if index < 0 {
			continue
		}
		printWithContext(splline, i, 5)
	}
	tw.Flush()
}