Skip to content

Instantly share code, notes, and snippets.

@jeremyvisser
Created October 15, 2017 22:12
Show Gist options
  • Save jeremyvisser/d8c802cbb96b953857b516a3805f7fa2 to your computer and use it in GitHub Desktop.
Save jeremyvisser/d8c802cbb96b953857b516a3805f7fa2 to your computer and use it in GitHub Desktop.
IOS–like "section" command
// Copyright 2017 Google 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
//
// https://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.
package main
import (
"bufio"
"fmt"
"os"
"strings"
"unicode"
)
func Readln(ch chan string, f *os.File) {
// Reads 'f' and outputs one line at a time to 'ch'
defer close(ch)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
ch <- scanner.Text()
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading stdin:", err)
}
}
func NotSpace(c rune) bool {
return !unicode.IsSpace(c)
}
func main() {
searchstr := strings.Join(os.Args[1:], " ")
ch := make(chan string, 16)
go Readln(ch, os.Stdin)
// Indent level where our search term is at
lvl := -1
for line := range ch {
// Find the current indent level
cur := strings.IndexFunc(line, NotSpace)
// Look for our search string and print it
if strings.Index(line, searchstr) != -1 {
fmt.Println(line)
// Save our indent level
if lvl == -1 || cur < lvl {
lvl = cur
}
} else {
if lvl != -1 && cur > lvl {
// If we're more indented than the search term, print line
fmt.Println(line)
} else {
// Found an outdented line. Cancel search.
lvl = -1
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment