From 5ed52f4eb2b60e1b1875f1ca9a465f248af36c7d Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Fri, 4 Aug 2017 18:06:05 -0400 Subject: [PATCH] Add "add link" shortcut --- writeas/AppDelegate.swift | 5 +++++ writeas/Base.lproj/Main.storyboard | 6 ++++++ writeas/ViewController.swift | 10 +++++++++- writeas/WindowController.swift | 3 +++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/writeas/AppDelegate.swift b/writeas/AppDelegate.swift index 1d6f392..5ca302d 100644 --- a/writeas/AppDelegate.swift +++ b/writeas/AppDelegate.swift @@ -95,6 +95,11 @@ class AppDelegate: NSObject, NSApplicationDelegate { wc?.emphasize() } + @IBAction func formatAddLink(_ sender: Any) { + let wc = NSApplication.shared().mainWindow?.windowController as? WindowController + wc?.addLink() + } + @IBAction func setFontSerif(_ sender: NSMenuItem) { deselectAllFonts() sender.state = NSOnState diff --git a/writeas/Base.lproj/Main.storyboard b/writeas/Base.lproj/Main.storyboard index 93dc51e..bef6379 100644 --- a/writeas/Base.lproj/Main.storyboard +++ b/writeas/Base.lproj/Main.storyboard @@ -333,6 +333,12 @@ DQ + + + + + + diff --git a/writeas/ViewController.swift b/writeas/ViewController.swift index 26b5069..5568d6d 100644 --- a/writeas/ViewController.swift +++ b/writeas/ViewController.swift @@ -94,18 +94,26 @@ class ViewController: NSViewController, NSTextViewDelegate, NSUserNotificationCe formatText(with: "_\(getSelectedText())_", offset: 1) } + func addLink() { + let text = getSelectedText() + formatText(with: "[\(text)](http://)", offset: text == "" ? 1 : (text.characters.count + 10), alwaysOffset: true) + } + fileprivate func getSelectedText() -> String { let selectedRange = writerText.selectedRange() return (self.writerText.textStorage?.string as! NSString).substring(with: selectedRange) } fileprivate func formatText(with: String, offset: Int) { + formatText(with: with, offset: offset, alwaysOffset: false) + } + fileprivate func formatText(with: String, offset: Int, alwaysOffset: Bool) { let selectedRange = writerText.selectedRange() let selString = getSelectedText() if self.writerText.shouldChangeText(in: selectedRange, replacementString: with) { self.writerText.replaceCharacters(in: NSRange(location: selectedRange.location, length: selectedRange.length), with: with) self.writerText.didChangeText() - if selString == "" { + if selString == "" || alwaysOffset { writerText.setSelectedRange(NSRange(location: selectedRange.location + offset, length: 0)) } } diff --git a/writeas/WindowController.swift b/writeas/WindowController.swift index e3ed13c..62925b3 100644 --- a/writeas/WindowController.swift +++ b/writeas/WindowController.swift @@ -34,4 +34,7 @@ class WindowController: NSWindowController { func emphasize() { vc?.emphasize() } + func addLink() { + vc?.addLink() + } }